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?
Using the spread operator or the concat() method is the most optimal solution. If you are sure that all inputs to merge are arrays, use spread operator . In case you are unsure, use the concat() method. You can use the push() method to merge arrays when you want to change one of the input arrays to merge.
The array method accepts an optional parameter depth , which specifies how deep a nested array structure should be flattened (default to 1 ). So to flatten an array of arbitrary depth, just call flat method with Infinity .
To combine two arrays into an array of objects, use map() from JavaScript.
Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
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'));
Do not know lodash or underscore, but you can use the native forEach and concat methods of Array (underscore may have equivalent methods, and polyfills for older browsers)
var data = [{
id: ...,
name: "...",
users: [1, 2, 3]
},
...
];
var allUsers = [];
data.forEach(function(obj){
allUsers = allUsers.concat(obj.users);
});
console.log(allUsers);
Demo
var data = [{
id: 1,
name: "...",
users: [1, 2, 3]
},
{
id: 2,
name: "....",
users: [4, 5, 6]
},
{
id: 3,
name: "...",
users: [7, 8, 9]
},
];
var allUsers = [];
data.forEach(function(obj){
allUsers = allUsers.concat(obj.users);
});
document.querySelector("#log").innerHTML = allUsers.join(",");
<div id="log"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With