m0ngr31 m0ngr31 - 3 months ago 13
Javascript Question

Combine nested arrays into one?

Let's say I have an array of objects that look similar to this:

[
{
id: ...,
name: "...",
users: [1, 2, 3]
},
...
]


Is there a way that I can easily merge the .users array of each object into one array?

Answer

Pluck 'n' flatten will do what you want:

var result = _.flatten(_.pluck(data, 'users'));

Edit

As Richard points out, pluck was removed from lodash in version 4.0.0 but still remains in the current version of underscore at time of writing (1.8.3).

Replacing pluck with map works for both lodash and underscore:

var result = _.flatten(_.map(data, 'users'));
Comments