javascript code to sort an array of objects within a nested array

I need assistance with removing the deleted status from the children key in a nested array of objects using JavaScript. Currently, when I try to filter out the deleted status, I receive an error stating "cannot return filter of undefined." The goal is to ensure that the children key within the obj variable only contains items with an Active status.

var obj = [
  {id:1, label: "sample", children: [{id: 0, status: "Active", name: "xyz"}, {id: 1, status: "Deleted", name: "abc"}]}
  {id:2, label: "example"},
  {id:3, label: "details", children: [{id:1, status: "Active", name: "finance"}]}
]

var result = removeDeleted(obj);

function removeDeleted(obj){
   if (obj.length > 0) {
    var list= obj.map(e => {
      e.children = e.children.map(child => {
        child.children = child.children.filter(c => 
          c['status'] !== "Deleted"       
        );
        return child
      });
      return e
    });
     return list;
  } 
}

Expected Output:
[
  {id:1, label: "sample", children: [{id: 0, status: "Active", name: "xyz"}]}
  {id:2, label: "example"},
  {id:3, label: "details", children: [{id:1, status: "Active", name: "finance"}]}
]


Answer №1

If you're looking for a solution, give this method a shot:

var data = [
  {id:1, label: "example", items: [{id: 0, status: "Active", name: "apple"}, {id: 1, status: "Deleted", name: "orange"}]},
  {id:2, label: "sample"},
  {id:3, label: "details", items: [{id:1, status: "Active", name: "finance"}]}
]

var updatedData = removeDeletedItems(data);
console.log(updatedData);
function removeDeletedItems(data){
   return data.map(item => {
     if(item.items){
        var filteredItems = item.items.filter(subItem => subItem.status != 'Deleted');
        return {id: item.id, label:item.label, items:filteredItems};
      }
     else return item;
   });
}

Answer №2

When dealing with multiple properties, it is advantageous to destructure them.

let data = [ {id:1, label: "example", children: [{id: 0, status: "Active", name: "xyz"}, {id: 1, status: "Deleted", name: "abc"}]}, {id:2, label: "sample"}, {id:3, label: "info", children: [{id:1, status: "Active", name: "finance"}]}];

let result = data.map(({children, ...rest})=>{
    if(children) children = children.filter(({status})=>status=='Active');
    if(children) return {...rest, children};
    return rest
});

console.log(result);

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

The customized message for parsley's minimum length is not being applied properly when passed as an option during binding

When attempting to bind the Parsley script to an input field, I am encountering an issue with the minlength message not displaying my custom one. Instead, the default error message from Parsley is being shown. I've tried adjusting the code but it does ...

When using the ajax method to pass data from the view to the controller, I encountered an issue where the data would unexpectedly become null once it reached the action

function UserLogin() { var username = $("#txtUsername").val(); var passcode = $("#txtPassword").val(); alert(username); $.ajax({ url: '@Url.Action("Login", "UserAccount")', ...

Unable to Retrieve Post Value in CodeIgniter 3

Today, I am working with CodeIgniter 3 and I need to retrieve post data from my view files. Below is the code from my view files: <form action="<?php echo base_url('action/getpost'); ?>" method="post"> <div class="row marketing"&g ...

How to style a div for printing using CSS

Currently, I am working on a project that has already been completed but now requires some enhancements. To give you an overview, the project includes a search functionality that displays additional details upon clicking on the displayed name in the result ...

Socket.io in Express is already assigned to another address

I'm having trouble getting my app to connect with Socket.io via websockets. Each time I attempt to run this code snippet, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 Despite checking for any other process ...

Maximizing the Efficiency of jQuery and Javascript Frameworks

Currently, I am working on a project that involves utilizing a JavaScript framework (jQuery) in conjunction with various plugins (validation, jquery-ui, datepicker, facebox, and more) to enhance the functionality of a modern web application. However, I ha ...

Concerning the usage of i values within Javascript loops

As a newcomer to Javascript, I have a basic question. I am attempting to create a for loop where new variables are generated based on the value of i. How can I dynamically change variable names using the i value (without resorting to an array)? For insta ...

A Guide to Effectively Extracting Data from Second Level JSON Arrays with

Hi, I'm having difficulty fetching the two attributes under CategoryImage in the second level of the JSON array parsing. Can someone help me with this? Thank you. <script> $(document).ready(function() { var cat=""; ...

Vue.js - display additional items in an array with matching titles

I am working with an array of objects, examples include: [{ title: 'foo' id: 1, name: 'anne' }, { title: 'example', id: 2, name: 'anne' }, { title: 'ex', id: 3, name: &a ...

Tips for waiting in webdriverjs until takeScreenshot captures the screenshot:

When capturing a screenshot using webdriverjs, I often face the issue of the screenshot being taken asynchronously, resulting in potential errors if an exception occurs before the screenshot is saved. The code snippet I typically use is as follows: var pr ...

I'm having issues with my Express.js API not being able to access the specified

My Express js server is not reading the res.body.signatureRequestId property. How can I submit this property to prevent the type error? I have shared my error log, JSON response, and Express js code below. Error log: { account: { account_id: ' ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

Is there a more efficient algorithm than O(N) for identifying the first set bit in a bit array primarily composed of contiguous blocks?

Imagine having a bitarray that is characterized by very low complexity, mainly consisting of continuous chunks of either "1"s or "0"s. In this array, the likelihood of two consecutive bits being the same is significantly higher than 50%. For instance: 000 ...

Tips for transferring objects from JavaScript/jQuery/angular to an action function

Issue at Hand: I currently have a form with 10 fields, and the challenge lies in passing these 10 values to an ASP.Net MVC Action. To tackle this, I utilize ng-click to send these values to the action which then forwards them to the database. I find myse ...

Is it possible to extract elements from a single list and insert them onto various pages?

Currently, I am retrieving items from a list using an ajax call. After constructing the HTML content, I insert these items onto a page. Now, I want to extract the same items and display them on another page with a different style. Is there a method to conn ...

Enhancing the Appearance of HTML Select Dropdowns in JavaFX 2.2 WebEngine

I am currently working on a project that is unable to be updated to Java 1.8 to support the latest JavaFX version. While this may or may not impact the issue I am facing, I have been exploring various solutions from the internet to customize the look and f ...

Having difficulty choosing an item from a personalized autocomplete search bar in my Vue.js/Vuetify.js project

NOTE: I have opted not to use v-autocomplete or v-combobox due to their limitations in meeting my specific requirements. I'm facing difficulties while setting up an autocomplete search bar. The search functionality works perfectly except for one mino ...

Retrieving JSON data without using Jquery's Ajax function

I was wondering if there is any way to retrieve the results of a jQuery AJAX call and store them in a traditional variable for use as a function. Here's an example: function getPoints(){ //An array of JSON objects var Points; ...

Executing a function from a JavaScript file within Robot Framework

It is possible to run javascript from a file. Run JavaScript ${CURDIR}/js_to_run.js However, I am wondering how to call a function by its name from this file? ...

Display several modal pop ups using AngularJS

I'm currently using AngularJS and I have a requirement where I need to check if a student ID exists in the database when a user clicks a button. If the student ID is found in the database, I want to display #modal1, otherwise show #modal2. Is it achie ...