简体   繁体   中英

convert multiple arrays objects to single array, underscore

I have an array which contain multiple objects, like

var val = [
    _id: ["5412fc1bd123cf7016674a92", "5412cf270e9ca9b517b43ca3"],
    _id: ["5412cf5a6cc4f4bc151fd220"]
];

I want to change to single array, like:

var val = [
    "5412fc1bd123cf7016674a92", 
    "5412cf270e9ca9b517b43ca3", 
    "5412cf5a6cc4f4bc151fd220"
];

I'm using _.pluck() but its not giving me the output which I want. How can I achieve this?

Update: This is 2019 and Array.flat is native.

 const val = { _id: ["5412fc1bd123cf7016674a92", "5412cf270e9ca9b517b43ca3"], _id2: ["5412cf5a6cc4f4bc151fd220"] } console.log( Object.values(val).flat() ) // Without flat console.log( Array.prototype.concat.apply( [], Object.values(val) ) ) // Without Object.values console.log( Array.prototype.concat.apply( [], Object.keys(val).map(k => val[k]) ) ) 

The following is all you need with lodash:

_.flatten(_.values(val))

Assuming your input data is an object containing several arrays, like so:

var val = {
    _id: ["5412fc1bd123cf7016674a92", "5412cf270e9ca9b517b43ca3"],
    _id2: ["5412cf5a6cc4f4bc151fd220"]
};

You can get the desired array structure pretty easily using concat :

var flat = [];
for (var key in val) {
    flat = flat.concat(val[key]);
}
console.log(flat);

Output:

[ '5412fc1bd123cf7016674a92',
  '5412cf270e9ca9b517b43ca3',
  '5412cf5a6cc4f4bc151fd220' ]

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