简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM