Get items in a multidimensional array-like object

Viewed 38

I have the following variable:

> let location = {0: {1: {name: 'Fred', age: 20}, 5: {name: 'Ema', age: 55}}, 9: {3: {name: 'John', age: 29}}};

And I want to get the items in it:

> console.log(get_items(location));
[{name: 'Fred', age: 20}, {name: 'Ema', age: 55}, {name: 'John', age: 29}]

I've written the following function:

function get_items(location) {
  return _.values(location).reduce((items, item)=> items.concat(_.values(item)), []);
}

But I wonder if there is a more elegant solution for this problem.

1 Answers

You could do this with Array#flatMap and Object#values

  • The Object#values will extract the value(s) of the outer object:
  • The Array#flatMap would map and flatten the nested objects into a single array of objects after extracting the value by applying the Object#values again for each object:

let data = {0: {1: {name: 'Fred', age: 20}, 5: {name: 'Ema', age: 55}}, 9: {3: {name: 'John', age: 29}}};
const transform = (data) => Object.values(data).flatMap(Object.values);

console.log(transform(data));

Related