How to find a object in a nested array using recursion in JS

后端 未结 7 831
慢半拍i
慢半拍i 2021-01-04 21:58

Consider the following deeply nested array:

const array = [
    {
        id: 1,
        name: \"bla\",
        children: [
            {
                id:         


        
相关标签:
7条回答
  • 2021-01-04 22:20

    This should work:

    function findByIdRecursive(array, id) {
      for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (element.id === id) {
          return element;
        } else {
          if (element.children) {
            const found = findByIdRecursive(element.children, id);
    
            if (found) {
              return found;
            }
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题