8

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

2
  • Single array of objects like mentioned in question. Edited question to visually show desired result also Commented Jan 17, 2018 at 16:25
  • do you just want to omit keys, a,b,c Commented Jan 17, 2018 at 16:25

4 Answers 4

4

You could concat the values of the object.

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

console.log(array);

Sign up to request clarification or add additional context in comments.

3 Comments

Indeed, Object.values() is better here :)
Not supported in ie, link
@Dhaval, the question has an arrow function inside, so op is using ES6.
2

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

1 Comment

save some typing by using arrow function and concat instead (inside the reduce), eg: reduce( (current, item) => current.concat( values[item] ) )
1

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

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

2 Comments

This would imply knowing the keys in advance, though.
Right. Good suggestion but I wont always know the keys
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.