I have a javascript object with several keys whose values are arrays of objects. I am trying to combine all key/values into a single array of objects. So from
{
a: [{}, {}, {}],
b: [{}, {}, {}],
c: [{}, {}, {}]
}
To
[{}, {}, {}, {}, {}, ...]
I am trying something like
Object.keys(myObject).map(key => myObject[key])
Which results in an array with 3 arrays inside.
I have also tried using using lodash and doing
Object.keys(myObject).map(key => _.values(myObject[key]))
Which seems to result in the same thing. How can I properly do this? Preferably in a single line like I am attempting instead of a loop. Sorry if this is asked already, I don't know how to word the question to find a result
Using the Spread operator We can use the spread operator on arrays within an array literal( [] ) to merge them. Let's see it with an example. First, we will take two arrays, arr1 and arr2 . Then merge the arrays using the spread operator( ... ) within an array literal.
To add a key/value pair to all objects in an array:Use the Array. map() method to iterate over the array. On each iteration, use the spread syntax to add the key/value pair to the current object. The key/value pair will get added to all objects in the new array.
How do you sum multiple objects with the same key in an array? First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'.
You could concat
the values of the object.
var object = { a: [{}, {}, {}], b: [{}, {}, {}], c: [{}, {}, {}] },
array = [].concat(...Object.values(object));
console.log(array);
You can use Array.prototype.reduce
to generate an array with all the nested objects (only one level of nesting is handled here, I don't know how much you want).
var values = {
a: [{}, {}, {}],
b: [{}, {}, {}],
c: [{}, {}, {}]
};
Object.keys(values).reduce(function(res, key) {
return res.concat(values[key]);
}, []); // [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
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