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

后端 未结 7 828
慢半拍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;
            }
          }
        }
      }
    }
    

提交回复
热议问题