如何显示特定类别id的孩子并最终压扁他们

问题描述 投票:0回答:0

我有这个数据

  const data = [
    {
      name: "Car",
      id: "19",
      count: "20",
      depth: "1",
      children: [
        {
          name: "Wheel",
          id: "22",
          count: "3",
          depth: "2",
          children: [
            {
              name: "Engine",
              id: "101",
              count: "1",
              depth: "3",
              children: [
                {
                  name: "Engine and Brakes",
                  id: "344",
                  count: "1",
                  depth: "4",
                  children: []
                }
              ]
            }
          ]
        }
      ]
    },
    {
      name: "Bike",
      id: "3",
      count: "12",
      depth: "1",
      children: [
        {
          name: "SpeedBike",
          id: "4",
          count: "12",
          depth: "2",
          children: []
        }
      ]
    }
  ];

我想传入多个类别 ID,如下所示 ['22', '3'] 并能够获取传递的类别 ID 的所有子项,它们应该如下所示:


[
  {
    name: "Engine",
    id: "101",
    count: "1",
  },
  {
    name: "Engine and Brakes",
    id: "344",
    count: "1",
  },
  {
    name: "SpeedBike",
    id: "4",
    count: "12",
  }
]

如果没有传递类别 ID,我希望能够默认看到父级和直接子级。如下所示:

[
 {  
    name: "Car",
    id: "19",
    count: "20"
 },
 {
    name: "Wheel",
    id: "22",
    count: "3"
 },
 {
    name: "Bike",
    id: "3",
    count: "12",
 },
 {
    name: "SpeedBike",
    id: "4",
    count: "12"
 }
]

如果传递的类别 id 没有孩子我想返回一个空数组。:

[]

我想避免使用

for
foreach
while
。我怎样才能做到这一点?我试过使用
map
filter
但没有运气。有人可以帮忙吗?最好的方法是什么?

我正在使用js和ts。

嵌套数组可以很深,有多个深度。

javascript arrays multidimensional-array mapping hierarchy
© www.soinside.com 2019 - 2024. All rights reserved.