Using JavaScript to sort through an array of nested objects

I'm working on extracting data from a deeply nested array.

Here's the initial setup:

layout: {
  parent: [
   {
    type: "tabset",
    id: "tab1",
    children: [
      {
        type: "tab",
        id: "id1",
      },
      {
        type: "tab",
        id: "id2",
      },
    ],
  },
  {
    type: "tabset",
    id: "tab2",
    children: [
      {
        type: "tab",
        id: "id3",
      },
    ],
  },
],},

I need to remove the object with id: "id2" from the input. Here is my attempt:

layout.parent.filter((item) => item.children.filter((el) => el.id !== "id2"));

The desired output:

layout: {
  parent: [
   {
    type: "tabset",
    id: "tab1",
    children: [
      {
        type: "tab",
        id: "id1",
      },
    ],
  },
  {
    type: "tabset",
    id: "tab2",
    children: [
      {
        type: "tab",
        id: "id3",
      },
    ],
  },
],},

Unfortunately, my code is not producing the desired outcome. Any suggestions or explanations would be greatly appreciated.

Thank you in advance for your help!

Answer №1

Update the child array by assigning the filtered version...

const layout = {
  parent: [{
      type: "tabset",
      id: "tab1",
      children: [{
          type: "tab",
          id: "id1",
        },
        {
          type: "tab",
          id: "id2",
        },
      ],
    },
    {
      type: "tabset",
      id: "tab2",
      children: [{
        type: "tab",
        id: "id3",
      }]
    }
  ]
}

layout.parent.forEach(parent => {
  parent.children = parent.children.filter(e => e.id !== 'id2')
})
console.log(layout)

Answer №2

Instead of altering the data, it's better to utilize it in its original form :)

If you want to manipulate the data, consider using Array#map & Array#filter as shown below

const layout = {parent: [{type: "tabset",id: "tab1",children: [{ type: "tab", id: "id1", }, { type: "tab",
 id: "id2", }, ],  },{ type: "tabset",id: "tab2", children: [ { type: "tab", id: "id3",}] }]};

const result = layout.parent.map(({type, id, children}) => 
              ({type, id, children: children.filter(c => c.id !== "id2")}));

console.log({parent: 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

How to set up a MySQL database specifically for a quiz based on different "types"

I am a beginner in the world of HTML, PHP, JavaScript, and MySQL. I have developed a quiz using JavaScript and HTML, but now I believe I need a database to store all the questions and answers. I am currently using PHPMyAdmin to set up the database and tabl ...

Utilizing an undefined constant in angular programming may lead to unexpected errors

Seeking assistance in generating random first and last names based on gender for a form using Angular. I am relatively new to Angular and keep encountering this error whenever the Use of undefined constant firstName - assumed 'firstName' Here ...

What is the best way to determine the total number of pages for posts

Hello there! I'm currently working on implementing an infinite scroll feature for a custom post type, but I'm stuck on how to obtain the max_num_pages and pass it to JavaScript. Below is my current implementation of the infinite scroll: containe ...

I updated the script to include a feature that automatically adds a leading zero to hours, minutes, and seconds if they are less than 10. However, for some reason, the output still doesn't show the leading zero

I have successfully created a countdown timer that works effectively. One of the conditions I added is to display leading zeros for hours, minutes, and seconds if they are less than 10. The desired format is like this (06 : 08 : 09) instead of (6 : 8 : 9 ...

Numerous query parameters sharing identical names

I am seeking information on how EXPRESS handles multiple query parameters with the same name. Despite my research efforts, I have been unable to find a reliable source on this topic. Specifically, I am interested in how EXPRESS would interpret a URL such ...

After the recent update to version 4.2.0 of @material-ui/core, unexpected react hook errors have been

Currently, I am working on an electron application that utilizes react and material-ui. Recently, I made the decision to update material-ui to version 4.2.0. As a result of this update, two lines were added to my dependencies in the package.json. "@materi ...

Why won't my software successfully change a series of integers into text format?

Can anyone help me figure out how to convert a list of integers (specifically the prime numbers) into a single string (not a list of strings)? I'm having trouble getting my program to display the desired output of "11-19". It's not even showing a ...

Leveraging window.hash and the power of WordPress htaccess

I have a Wordpress website where I am using Ajax to display posts in a specific section. I am currently having Javascript add the hash tag like this: window.location.hash = id; Everything is working as expected. For instance, it changes the URL to www.my ...

A warning message has been triggered: 'Script Alert Error - Object

I've been putting in hours on a SUP project that requires some tweaking and I keep running into the issue Script Alert Error: Object expected The code I've added is: $('#bottomOfStart_ScreenForm').before('<div style="display: ...

Wait for NodeJS to finish executing the mySQL query

I am attempting to send an object from the controller to the view. To keep my queries separate from the controller, I am loading a JS object (model). My model structure is as follows: function MyDatabase(req) { this._request = req; this._connection = ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in: ...

Exploring the Safari browser with Polymer 2.0

Looking for some help with a question I have... I've been experimenting with the new Polymer 2.0 preview on Safari, but it doesn't seem to be working correctly. I'm using a simple code (just my-element) in the index.htm file, loading the pol ...

Ways to restrict a function to a single DOM element using either its id or class

This script is responsible for dynamically loading pages on my website. It works fine, except that it currently iterates over all anchor tags a on the site, whereas I want it to iterate only through my navigation menu. Here is the navigation menu: <div ...

Determine the path of the file that triggered the execution of another file

I am looking to retrieve the file path of the file that executed another file. first.js const second = require("./second.js"); exports.run = () => { second.run(); } second.js exports.run = () => { let executedPath; // <-- ? con ...

"Exploring the Power of Primefaces Dialog Framework: Unleashing the dialogReturn Event

I'm working with a primefaces p:datatable in Table.xhtml and have a p:commandbutton on the same page that triggers a dialog using the dialog framework. The dialog content is in Dialog.xhtml. Both the Table.xhtml and Dialog.xhtml are using a single bac ...

Retrieve a row from a table if a value from an array in another table exists

I have a pair of tables. Users table includes columns member_group which can be Admin Marketing Sales zone which can be North West East Meetings table includes columns for_member_group for_zone columns. for_member_group and for_zone may ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

Splitting with Regex - One Time Operation

Here is some of my Jquery code along with Regex: $("[class^=ipsum-img],[class^=ipsum-img-]").each(function(){ var x = $(this).attr("class"); console.log(x.length); if (x.length>8) { var m = x.split(/(\d+)[^-]*$/g); cons ...

Is it possible to dynamically evaluate the fs argument?

When I tried to run npm run dev, I encountered the following error: An error occurred while attempting to evaluate the fs argument statically [0] 50 | // Read file and split into lines [0] 51 | var map = {}, [0] > 52 | content = fs.read ...