简体   繁体   中英

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

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

在ES6中,如果已知密钥,您只需执行以下操作:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM