3

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
  • what is the output of your code? Commented Apr 1, 2021 at 3:00
  • @majurageerthan It is the same as my input :((( Commented Apr 1, 2021 at 3:15

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Does this answer your question? Let me know if you need any help ^^! Don't forget to accept my answer if it was useful to you @@dacoten

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.