quirky purple
quirky purple

Reputation: 2219

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

Upvotes: 8

Views: 8040

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386560

You could concat the values of the object.

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

console.log(array);

Upvotes: 4

T.Liu
T.Liu

Reputation: 512

You could concatenate arrays in JavaScript. Here is a solution to your question:

var data = {
    a: [{}, {}, {}],
    b: [{}, {}, {}],
    c: [{}, {}, {}]
}

var result = [];

for (var key in data ){
   result = result.concat(data [key]);
}

console.log(result);

Upvotes: 0

Rafael Quintanilha
Rafael Quintanilha

Reputation: 1432

In ES6, if keys are known, you can simply do:

const array = [...obj.a, ...obj.b, ...obj.c];

Upvotes: 1

kLabz
kLabz

Reputation: 1847

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]);
}, []); // [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

Upvotes: 2

Related Questions