使用JavaScript过滤数组中的嵌套对象

3

我正在尝试从一个嵌套数组中获取数据。

我的输入:

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

我只想从我的输入中删除ID为"id2"的对象,以下是我的代码:

我只想从我的输入中删除ID为"id2"的对象,以下是我的代码:

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

我想要的输出:

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

但我的代码运行不正常,请帮我解释并提供一些新的解决方法。

非常感谢。


你的代码输出是什么? - majurageerthan
@majurageerthan 这和我的输入一样 :((( - dacoten
2个回答

1
使用赋值操作将子数组替换为过滤版本...

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)


1
个人认为,我们应该使用数据而不是改变它 :)

您可以像这样使用Array#mapArray#filter

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


这个回答解决了您的问题吗?如果需要任何帮助,请告诉我^^!如果我的回答对您有用,请不要忘记接受它@@dacoten - Nguyễn Văn Phong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接