Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering nested object in array using JavaScript

I am trying to get data from a nested array.

My input:

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 only want to remove object with id: "id2" from my input and here is my code:

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

The output that I want:

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

But my code does not works fine. Please help me explain and suggest some new ways to resolve it.

Thank you so much

like image 513
dacoten Avatar asked Feb 21 '26 17:02

dacoten


2 Answers

Replace the child array with the filtered version using assignment...

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)
like image 50
danh Avatar answered Feb 24 '26 07:02

danh


Personally, we should use data instead of mutating it :)

You can use Array#map & Array#filter like this

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});
like image 40
Nguyễn Văn Phong Avatar answered Feb 24 '26 05:02

Nguyễn Văn Phong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!