简体   繁体   English

在深度未知的嵌套数组中查找具有特定值的元素

[英]Find elements with specific value in a nested array with unknown depth

I have an array with objects for which the nesting depth is unknown and can be different.我有一个包含嵌套深度未知并且可以不同的对象的数组。 An example of such an array looks like that:这种数组的一个示例如下所示:

let exampleArray = [
  {
    id: 'some-id',
    label: "Item 1",
    children: [
      {
        id: 'some-id',
        label: "Child 1",
        children: [
          {
            id: 'some-id', // How to find this for example?
            label: "Child 2",
            children: []
          }
        ]
      }
    ]
  },
  {
    id: 'some-id',
    label: "Item 2",
    children: [
      {
        id: 'some-id',
        label: "Child 1",
        children: [
          {
            id: 'some-id',
            label: "Child 2",
            children: []
          }
        ]
      }
    ]
  }
]

Each array item can have a nested array children .每个数组项都可以有一个嵌套数组children The basic structure is the same as the parent one.基本结构与父级相同。

The challenge挑战

When I for example want to delete a nested element with a specific id, how could I do this?例如,当我想删除具有特定 id 的嵌套元素时,我该怎么做? I think it would not be the best practice to start iterations with a static number of loops, because I don't know how big the array is nested.我认为使用 static 循环数开始迭代不是最佳实践,因为我不知道嵌套的数组有多大。

If I know the ID from the children element, can I say something like: "Iterate the entire array including all nesting and find the element with the ID xy?".如果我知道子元素的 ID,我可以这样说: “迭代包括所有嵌套在内的整个数组并找到 ID 为 xy 的元素?”。

Or what would be the best practice to handle such nested arrays?或者处理这种嵌套的 arrays 的最佳做法是什么?

A recursive function is likely what you're looking for:递归 function 可能是您正在寻找的:

function deleteById(data, id){
    for(var x = 0; x < data.length; x++){
        if(data[x].id === id){
            data.splice(x, 1); // if it matches, remove it from the array
        }
        else{
            deleteById(data[x].children, id);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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