简体   繁体   中英

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 . 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? 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.

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?".

Or what would be the best practice to handle such nested arrays?

A recursive function is likely what you're looking for:

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

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