Remove any objects from the array that have empty values when filtered

I am facing a challenge with filtering objects in an array. Each object contains a title and rows, where the rows also have a risk value (like P1, P2, P3, etc.). My goal is to extract only the rows that have a risk equal to P1 while skipping any objects that do not contain any P1 risks.

let data = [ 
    {
        "title": "QA",
        "rows": [
            {
                "risk": "P3",
                "Title": "Permission issue",
            }
        ]
    }, 
    {
        "title": "Prod",
        "rows": [
            {
                "risk": "P5",
                "Title": "Console log errors fix",
            },
            {
                "risk": "P1",
                "Title": "Server is in hung state",
            }
        ]
    }
]

The desired result should look like this:

    {
        "title": "Prod",
        "rows": [
            {
                "risk": "P1",
                "Title": "Server is in hung state",
            }
        ]
    }
]

Currently, the code I tried includes titles even if they do not have any P1 risks. Can someone provide a solution to filter out objects without P1 risks entirely?

Answer №1

Create a fresh list by filtering out items with P1 risk in their rows.

data.reduce((accumulator, element) => {
  const filteredRows = element.rows.filter(rowItem => rowItem.risk === 'P1');
  if (filteredRows.length === 0) return accumulator;
  return [...accumulator, {...element, filteredRows }]
}, [])

Answer №2

To easily remove objects that do not have the specific risk level of "P1", you can leverage the power of Array.prototype.filter function.

const data = [     {        "title": "QA",        "rows": [            {                "risk": "P3",                "Title": "Permission issue",            }        ]    },     {        "title": "Prod",        "rows": [            {                "risk": "P5",                "Title": "Console log errors fix",            },            {                "risk": "P1",                "Title": "Server is in hung state",            }        ]    }],
      result = structuredClone(data).filter(o => {
        o.rows = o.rows.filter(({risk}) => risk === "P1");
        return !!o.rows.length;
      });
      
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Instead of relying on a map, I recommend utilizing a filter method to achieve the desired outcome:

const result = data.filter((obj) => {
  let includesP1 = false;
  obj.rows.forEach((r) => {
    if (r.risk === "P1") includesP1 = true;
  });
  return includesP1;
});

Answer №4

By utilizing the reduce function, you can easily eliminate any non P1 risks from your dataset.

const data = [
  { title: "QA", rows: [{ risk: "P3", Title: "Permission issue" }] },
  {
    title: "Prod",
    rows: [
      { risk: "P5", Title: "Console log errors fix" },
      { risk: "P1", Title: "Server is in hung state" },
    ],
  },
];

const result = data.reduce((acc, d) => {
  const rows = d.rows.filter(({ risk }) => risk === "P1");
  if (rows.length) {
    acc.push({ ...d, rows });
  }
  return acc;
}, []);

console.log(result);

An Alternative Method

You could also first filter out the data containing at least one instance of a P1 risk, followed by removing all other non P1 risks from the filtered data.

const data = [
  { title: "QA", rows: [{ risk: "P3", Title: "Permission issue" }] },
  {
    title: "Prod",
    rows: [
      { risk: "P5", Title: "Console log errors fix" },
      { risk: "P1", Title: "Server is in hung state" },
    ],
  },
];

const result = data
  .filter(({ rows }) => rows?.some(({ risk }) => risk === "P1"))
  .map((d) => ({ ...d, rows: d.rows.filter(({ risk }) => risk === "P1") }));

console.log(result);

Helpful Resources:

Answer №5

To achieve this, the following steps can be taken:


  // A function is created to check if a row has risk P1
  const hasRiskP1 = (row) => { return row.risk === 'P1' };

  // The code filters out all rows that do not contain P1
  // Then it filters out any entries that do not have any rows left
  const result = data.map(entry => ({...entry, ...{rows: entry.rows.filter(hasRiskP1)}}))
                     .filter(entry => entry.rows.length);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for PHP to process a multidimensional array being submitted via $_POST along with another field serving as a key in the same form

My web form includes two select fields: "user_id[]" and "equipment_id[]. Here are some key points: I use a Javascript function to duplicate the group of "user_id[]" and "equipment_id[] fields each time I want to add another set. The "user_id[]" field all ...

Troubleshooting an Ajax request in Google Scripts with a '$' variable bug

I am trying to implement an AJAX Request using the ajax() method. I have created the functions below on scripts.google.com, but encountered the following error: function AjaxCall() { var arr = { City: 'Moscow', Age: 25 }; $.ajax({ u ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

What is the best way to extract a specific field from a JSON object using Node.js?

Here is how the JSON object looks with the TEMP field that I am attempting to retrieve: [ [ { "DEVICE_ID": "357807272", "TEMP": 20.439 } ] ] ...

How can you convert a JavaScript object with nested arrays into JSON format?

I have been working with a JavaScript object that contains nested objects with associative arrays. I attempted to use the stringify function from the json2.js library, but the output did not include the arrays inside the nested objects. In my scenario, I b ...

Breaking apart a pipe-separated text and sending it through a JavaScript function

CSS: <div class="pageEdit" value="Update|1234567|CLOTHES=5678~-9876543?|5678"> <a href="https://host:controller">Update</a> </div> Trying to retrieve the data within the div and pass it into a JavaScr ...

Exploring the Unpredictable Results of Recursive Functions in JavaScript

Take a look at this recursive code snippet. function calculateFactorial(n) { if (n === 0 || n === 1) { return 1; } else { console.log(calculateFactorial( (n - 1) )); return n * calculateFactorial(n - 1); } } const num = ...

Is there a way for me to store the output of an AJAX call?

One of the challenges I'm facing involves an AJAX request: $.ajax({ url: 'script.php?val1=' + value1 + '&val2=' + value2, dataType: "json", success: function (data) { var newValue1 = data[0]; ...

Guide to transforming a multi-dimensional array into JSON format for jqPlot chart in ASP.NET MVC using C#

I need the JSON data to follow this specific format: var data = [ ['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14], ['Out of home', 16],['Commuting', 7], ['Orienta ...

Optimizing JavaScript for efficient handling of large arrays

I'm currently developing an image editing program using JavaScript to expand my knowledge of the language. The images I am working with are typically around 3000 x 4000 pixels in size, resulting in a total of 48,000,000 values to manage when convertin ...

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

Mastering image focus with javascript: A comprehensive guide

On my HTML page, I have two images and a textbox. I want the focus to shift between the images based on the first character entered in the textbox. For example, when the user types '3', the first image should be focused, and for '4', th ...

Using AJAX to invoke a REST service endpoint

I'm currently implementing a REST service call using AJAX. $(document).ready(function () { var xmml = getXmlLoginRequest(); var wsdlURL = getWSDL('search'); $.ajax({ type: "POST", url: wsdlURL ...

What is the best way to retrieve an image using JSON within a ListFragment?

I recently started developing apps for Android and I'm using JSON Parsing to retrieve my data. I've extended my class with List Fragment and everything works fine except for displaying images in the list view. Here's a snippet of my response ...

Submit numerous queries to verify the presence of a name and assign it to the name attribute

I have a collection of unique devices. As part of a process, I need to assign a default name to each device ("DeviceX" - where X is a sequential number), but some of the names may already be in use. To handle this, I must make a request to check ...

Experiencing issues with autoungrabify or autolock in cytoscape.js?

I have been working on a web application using Cytoscape.js, and I recently integrated the Edgehandles extension to allow users to add edges. The two types of edges that can be added are undirected and directed. Adding directed edges is functioning as expe ...

Searching in React can be done dynamically by referencing an array, similar to how the "LIKE" function works in SQL

Currently, I'm tackling an issue with a dropdown feature. My goal is to have the dropdown results sorted when the user enters something into the input field. The values in the dropdown are sourced from an array. For instance, codeList = [N1, N2, N3, ...

Retrieving every piece of information from Kendo Grid's data source

After following a tutorial on exporting Kendo Grid Data, I am now attempting to export all data, not just the data shown on the page. How can I accomplish this task? I attempted to change the page size before retrieving the data: grid.dataSource.pageSize ...

Encountering a 500 server error while attempting to retrieve content from Google Images through the Web Speech API

My current project involves utilizing the Web Speech API to dynamically gather free images from Google. Here's how it works: I extract the search keyword using the Web Speech API in JavaScript. The keyword is then sent to the server (PHP) via an a ...