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
x
13
13
1
var data = [
2
{ text: 'Item 1', },
3
{ text: 'Item 2', },
4
{
5
text: 'More',
6
children: [
7
{ text: 'More 1', children: [] },
8
{ text: 'More 2'},
9
{ text: 'Other', children:[ {text: 'Other-1'}, {text: 'Other-2'}, {text: 'Other-3'} ] }
10
]
11
}
12
];
13
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
1
18
18
1
const _ = require('lodash');
2
const data = data = [
3
{ text: 'Item 1', },
4
{ text: 'Item 2', },
5
{
6
text: 'More',
7
children: [
8
{ text: 'More 1', children: [] },
9
{ text: 'More 2'},
10
{ text: 'Other', children:[ {text: 'Other-1'}, {text: 'Other-2'}, {text: 'Other-3'} ] }
11
]
12
}
13
];
14
15
const widget = _.get(obj, '[2].children[1]');
16
17
console.log('widget',widget);
18
Or… roll your own. It’s not that hard to walk the tree:
JavaScript
1
14
14
1
function select(data, path) {
2
let i = path.shift() ;
3
let node = data[i] ;
4
5
while ( node && (i=path.shift()) !== undefined ) {
6
node = node?.children?.[i] ;
7
}
8
9
return node ;
10
}
11
12
const widget = select( data, 2, 1 );
13
console.log(widget);
14