Filtering nested object in array using JavaScript

Viewed 115

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

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)

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});

Related