Skip to content
Advertisement

Walk through a nested array using index in JavaScript

I want walk through a nested array and need to find the target element in the array. An example path [2, 1] should return {text: 'More 2'} and path [2, 2, 1] should return { text: 'Other-2' }. I tried lodash functions but no luck yet. My Nested array is given below:

JavaScript

Advertisement

Answer

Well, it’s not a multi-dimensional array, nor is it a raggedy array-of-arrays. It’s an array of objects (that happen contain other arrays of objects that happen to…).

Lodash’s _.get() ought to do the trick for you:

JavaScript

Or… roll your own. It’s not that hard to walk the tree:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement