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:

var data = [
  { text: 'Item 1', },
  { text: 'Item 2', },
  {
    text: 'More',
    children: [
      { text: 'More 1', children: [] },
      { text: 'More 2'},
      { text: 'Other', children:[ {text: 'Other-1'}, {text: 'Other-2'}, {text: 'Other-3'} ] }
    ]
  }
];

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:

const _ = require('lodash');
const data = data = [
  { text: 'Item 1', },
  { text: 'Item 2', },
  {
    text: 'More',
    children: [
      { text: 'More 1', children: [] },
      { text: 'More 2'},
      { text: 'Other', children:[ {text: 'Other-1'}, {text: 'Other-2'}, {text: 'Other-3'} ] }
    ]
  }
];

const widget = _.get(obj, '[2].children[1]');

console.log('widget',widget);

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

function select(data, ...path) {
  let i    = path.shift() ;
  let node = data[i] ;

  while ( node && (i=path.shift()) !== undefined ) {
    node = node?.children?.[i] ;
  }

  return node ;
}

const widget = select( data, 2, 1 );
console.log(widget);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement