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

javascript recursive function array
create a nested array recursively in javascript
how to get parent object from child object in javascript
recursive function javascript
recursive build tree javascript
javascript recursive loop through array
javascript recursive array of objects
javascript find value in nested object

Consider the following deeply nested array:

const array = [
    {
        id: 1,
        name: "bla",
        children: [
            {
                id: 23,
                name: "bla",
                children: [{ id: 88, name: "bla" }, { id: 99, name: "bla" }]
            },
            { id: 43, name: "bla" },
            {
                id: 45,
                name: "bla",
                children: [{ id: 43, name: "bla" }, { id: 46, name: "bla" }]
            }
        ]
    },
    {
        id: 12,
        name: "bla",
        children: [
            {
                id: 232,
                name: "bla",
                children: [{ id: 848, name: "bla" }, { id: 959, name: "bla" }]
            },
            { id: 433, name: "bla" },
            {
                id: 445,
                name: "bla",
                children: [
                    { id: 443, name: "bla" },
                    {
                        id: 456,
                        name: "bla",
                        children: [
                            {
                                id: 97,
                                name: "bla"
                            },
                            {
                                id: 56,
                                name: "bla"
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        id: 15,
        name: "bla",
        children: [
            {
                id: 263,
                name: "bla",
                children: [{ id: 868, name: "bla" }, { id: 979, name: "bla" }]
            },
            { id: 483, name: "bla" },
            {
                id: 445,
                name: "bla",
                children: [{ id: 423, name: "bla" }, { id: 436, name: "bla" }]
            }
        ]
    }
];

How would I grab a certain object by key that might be deeply nested, using recursion? I have tried this, but this won't work for nesting deeper than 2 levels, it then just returns undefined:

const findItemNested = (arr, itemId, nestingKey) => {
    for (const i of arr) {
        console.log(i.id);
        if (i.id === itemId) {
            return i;
        }
        if (i[nestingKey]) {
            findItemNested(i[nestingKey], itemId, nestingKey);
        }
    }
};

The result should be:

const res = findItemNested(array, 959, "children"); >> { id: 959, name: "bla" }

This can perhaps also be achieved using .find, or just to flatten the array (by the children key), but using recursion seems like the most logical solution to me. Does anybody have a solution to this?

Thanks in advance :).

You might use a recursive reduce:

const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];

const findItemNested = (arr, itemId, nestingKey) => (
  arr.reduce((a, item) => {
    if (a) return a;
    if (item.id === itemId) return item;
    if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
  }, null)
);
const res = findItemNested(array, 959, "children");
console.log(res);

Js Looping And Iteration Traversing, To do so, we'll make a « getObject » recursive function to find our object in the datas object. The idea here is to make a first call to our recursive function from the click event. We pass the datas. tree array, the id of the DOM object and a callback as parameters. Or it’s an object with N subdepartments – then we can make N recursive calls to get the sum for each of the subdeps and combine the results. The 1st case is the base of recursion, the trivial case, when we get an array. The 2nd case when we get an object is the recursive step. A complex task is split into subtasks for smaller departments.

You might also use recursion with Array.find like below

const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];


function findById(arr, id, nestingKey) {
  
  // if empty array then return
  if(arr.length == 0) return
  
  // return element if found else collect all children(or other nestedKey) array and run this function
  return arr.find(d => d.id == id) 
      || findById(arr.flatMap(d => d[nestingKey] || []), id) 
      || 'Not found'
}

console.log(findById(array, 12, 'children'))

console.log(findById(array, 483, 'children'))

console.log(findById(array, 1200, 'children'))

How to « find deep » and « get parent » in JavaScript nested objects , Create a nested array recursively in Javascript. Let's say you have an array like this: [ {id: 1 And you want to have the objects nested like this: So far, all the arrays we’ve dealt with have been “flat” arrays; each array element contains a single value, such as a number, string, or object. However, like most programming languages, JavaScript lets you create arrays inside arrays, known as nested arrays. In a nested array, the elements of one array are themselves arrays. For example:

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

Create a nested array recursively in Javascript, For example, to calculate pow(2, 4) the recursive variant does these steps: The first idea may be to make a for loop over company with nested subloop over Either it's a “simple” department with an array of people – then we can sum the The linked list element is recursively defined as an object with:. Create a nested array recursively in Javascript. And you want to have the objects nested like this: Create a nested array recursively in CoffeeScript;

You can do:

const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];
const findItemNested = (arr, itemId, nestingKey) => arr.reduce((a, c) => {
  return a.length
    ? a
    : c.id === itemId
      ? a.concat(c)
      : c[nestingKey]
        ? a.concat(findItemNested(c[nestingKey], itemId, nestingKey))
        : a
}, []);
const res = findItemNested(array, 959, "children");

if (res.length) {
  console.log(res[0]);
}

Recursion and stack, depth Optional: The depth level specifying how deep a nested array A new array with the sub-array elements concatenated into it. 2, [3, 4, [5, 6]]]; // to enable deep level flatten use recursion with reduce and concat Array.prototype​.fill() · Array.prototype.filter() · Array.prototype.find() Object.prototype. This will use recursive find by level, it'll try to find the item in array and then call itself with the children of each item in the array: New browsers will have Array.prototype.flatten but in this case I've added the flatten function separately.

This will use recursive find by level, it'll try to find the item in array and then call itself with the children of each item in the array:

New browsers will have Array.prototype.flatten but in this case I've added the flatten function separately.

const array = [{"id":1,"name":"bla","children":[{"id":23,"name":"bla","children":[{"id":88,"name":"bla"},{"id":99,"name":"bla"}]},{"id":43,"name":"bla"},{"id":45,"name":"bla","children":[{"id":43,"name":"bla"},{"id":46,"name":"bla"}]}]},{"id":12,"name":"bla","children":[{"id":232,"name":"bla","children":[{"id":848,"name":"bla"},{"id":959,"name":"bla"}]},{"id":433,"name":"bla"},{"id":445,"name":"bla","children":[{"id":443,"name":"bla"},{"id":456,"name":"bla","children":[{"id":97,"name":"bla"},{"id":56,"name":"bla"}]}]}]},{"id":15,"name":"bla","children":[{"id":263,"name":"bla","children":[{"id":868,"name":"bla"},{"id":979,"name":"bla"}]},{"id":483,"name":"bla"},{"id":445,"name":"bla","children":[{"id":423,"name":"bla"},{"id":436,"name":"bla"}]}]}];


const flatten = (arr) =>
  arr.reduce((result, item) => result.concat(item), []);
const findBy = (findFunction, subItemsKey) => (array) =>
  //array is empty (can be when children of children of children does not exist)
  array.length === 0
    ? undefined //return undefined when array is empty
    : array.find(findFunction) || //return item if found
      findBy(findFunction, subItemsKey)(//call itself when item is not found
        flatten(
          //take children from each item and flatten it
          //([[child],[child,child]])=>[child,child,child]
          array.map((item) => item[subItemsKey] || []),
        ),
      );
const findChildrenById = (array) => (value) =>
  findBy((item) => item.id === value, 'children')(array);
const findInArray = findChildrenById(array);

console.log('found', findInArray(99));
console.log('not found', findInArray({}));

Array.prototype.flat(), Advance your JS skills in this free course by learning higher order functions, Multidimensional arrays are a special kind of nested data structure, which To see if a value is an array, you can not use typeof since that will return 'object' , so one this is an excellent use case for recursion (writing a function that calls itself​). Giraffe Academy is rebranding! I've decided to re-focus the brand of this channel to highlight myself as a developer and teacher! The newly minted Mike Dane channel will have all the same content

Nested Arrays, in JS. Not anymore! ES2019 introduced a new method that flattens arrays with Array.flat(). Recursion. For arrays with deeper nesting, you can use recursion. To do so, we’ll make a « getObject » recursive function to find our object in the datas object. The idea here is to make a first call to our recursive function from the click event. We pass the datas.tree array, the id of the DOM object and a callback as parameters. If the recursive function finds our object, it calls the callback.

Flatten Array using Array.flat() in JavaScript, I am trying to create a function to access values within a reoccurring object nested within arrays of itself. For example: // Recursive nested  JavaScript - Using Recursion To Print Out Nested Objects - Free JavaScript Tutorials, Help, Tips, Tricks, and More.

Need help with JavaScript recursive nested objects & arrays , Expressions · Operators · Control Structures · Functions · Classes and Objects How to modify external variable from inside recursive function using userdata A simple solution for walking a nested array to obtain the last set value of a you will get a warning saying that "call-time pass-by-reference" is deprecated when  See the Pen javascript-recursion-function-exercise-4 by w3resource (@w3resource) on CodePen. Improve this sample solution and post your code through Disqus Previous: Write a JavaScript program to get the integers in range (x, y).

Comments
  • You need to return the inner findItemNested call, otherwise its return value is discarded.
  • Yep, that's one thing I've been doing wrong, thanks!
  • I don't understand when "a" var in reduce function is affected ?!
  • The a is the accumulator, the value returned from the last iteration. If truthy, a match has been found.on a past iteration, and gets returned to the next iteration. If falsy, a match hasn't been found yet, so the reduce either returns the current item if it's a match: return item or it searches for a recursive match with return findItemNested(....