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

Ways to update a single column in an HTML table when there is a change

I'm stuck trying to find a more efficient method for updating a column in an html table without having to reload the entire table. The table consists of player stats, all pulled from my MYSQL database and displayed in the table except for the last col ...

Negative vibes with for/in loop

My script is short and simple: hideElements = arguments.shift().split(','); for (iterator in hideElements) { console.log('--> hiding ' + hideElements[iterator]); lg_transitions({kind:"slide-up"}, {target: hideElements[iterat ...

Using a promise instead of resolving it with Angular's $q.then() methodology

Imagine you come across the given code snippet: var callNo1 = $http(...).then(function (response1) { var callNo2 = $http(...).then(function (response2) { return [response1.data, response2.data]; }); return callNo2; }).then(function (r ...

I am experiencing difficulty in detecting variable changes within my $scope function

I'm encountering an issue where a variable isn't being updated in a $scope function when there's a state change event. Despite seeing the variable update in the event listener, it doesn't reflect in the function. The code snippet in qu ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...

req.next does not exist as a function [END]

I am currently working on developing a website and I have encountered an issue in the dashboard stage. The error message TypeError: req.next is not a function keeps appearing, particularly when trying to create a subpage for the dashboard. I am utilizing t ...

Attempting to share a message via Curl

My experience with Curl is limited, and I find myself a bit confused. I'm attempting to extract the information from my form and post it to the URL specified in my CURLOPT_URL. In postman, I can successfully post basic Json using the following code: ...

Tips for integrating custom images or icons into Onsen-UI:

I am currently utilizing the Onsen-UI framework along with AngularJS to create a mobile application. I want to incorporate custom images for buttons, but they appear blurry or unclear on certain mobile devices when the app is launched. Below is my code sn ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

The fadein feature in Deps.Autorun is not functioning as expected in Meteor version 0.5.9

Here is the code I am currently working with: Template.jobFlash.helpers({ latest_job: function(){ if(Session.get("latestJob")!=""){ return JobsCollection.findOne({}, {sort: {'added_date': -1}}); } } }); Deps. ...

The following error occurred: Next Auth TypeError: URL is not valid

Every time I run my Nextjs project, I keep encountering an issue related to Next Auth. Despite using version 4.3.1, I am unsure about how to resolve it. Any assistance with next-auth would be greatly appreciated. Although I attempted to update my next-aut ...

Encountered an issue when trying to establish a connection to the MySQL database on Openshift using a

I am currently running a Node.js app with Express that is deployed on OpenShift. I have set up databases using the PHPMyAdmin 4.0 cartridge. Although I can establish a connection to the database, anytime I run a query, it throws an ECONNREFUSED error. Whe ...

Utilizing the Loess npm module in conjunction with Angular 4

I am attempting to incorporate the Loess package into my project. The package can be found on NPM and offers various regression models for data fitting. I successfully installed it using npm install loess --save, and it now resides in the node_modules dire ...

One issue with my Quiz app is that sometimes the correct and incorrect answer methods run concurrently, leading to occasional occurrences of this problem

One issue I encountered while developing a Quiz app is that sometimes the methods for correct and incorrect answers run simultaneously. This problem occurs sporadically. I want to highlight that my code is functioning correctly. The only challenge I face ...

Guide to making a button in jQuery that triggers a function with arguments

I've been working on creating a button in jQuery with an onClick event that calls a function and passes some parameters. Here's what I have tried so far: let userArray = []; userArray['recipient_name'] = recipient_name.value; userArray[ ...

I've encountered some issues with importing pagination from modules after installing SwiperJs

Having some issues with importing pagination from modules in SwiperJs for my nextjs project. The error message "Module not found: Package path ./modules is not exported from package" keeps popping up. I have tried updating the module to the latest version ...

Utilize Vue to localize the click events of buttons on the webpage

I have a scenario where I have several buttons on a page, and when I click one to toggle its text, all of the buttons change. How can I utilize VUE to isolate functionality and make each button's @click event only affect the clicked button? In the cod ...

Anticipated the server's HTML to have a corresponding "a" tag within it

Recently encountering an error in my React and Next.js code, but struggling to pinpoint its origin. Expected server HTML to contain a matching "a" element within the component stack. "a" "p" "a" I suspect it may be originating from this section of my c ...

Unable to interact with a button through JavaScript using execute_script in Selenium

https://i.stack.imgur.com/hJmtK.png I am attempting to remove a cookies popup by accepting the cookies and clicking confirm. While I am able to click an input labeled "zgadzam się na", for some reason, clicking a button with the label "potwierdź" appears ...

Obtain the attribute value from an HTML option element

Here is the code snippet I am working with: <select class="form-control valid"> <option isday="False" value="2">Value 1</option> <option isday="True" value="3">Value 2</option> <option isday="True" value="4"> ...