Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine object key/value into single array?

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

like image 378
wizloc Avatar asked Jan 17 '18 16:01

wizloc


People also ask

How do you merge objects into an array?

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.

How do I add a key-value to an array of objects?

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?

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'.


2 Answers

You could concat the values of the object.

var object = { a: [{}, {}, {}], b: [{}, {}, {}], c: [{}, {}, {}] },
    array = [].concat(...Object.values(object));

console.log(array);
like image 166
Nina Scholz Avatar answered Oct 08 '22 06:10

Nina Scholz


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]);
}, []); // [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
like image 21
kLabz Avatar answered Oct 08 '22 06:10

kLabz