Reputation: 7334
Suppose i have an object whose values are arrays just like this:
obj = {
'key1': [1,2],
'key2': [3,4],
'key3': [5,6],
}
How to i merge all the arrays of the object into one using concat. The number of keys of the object is dynamic of course but it will have at least one instance The desired output is this:
[1,2,3,4,5,6]
Upvotes: 2
Views: 173
Reputation: 15530
flat()
on Object.values()
is supposed to do the job:
const obj = {
key1: [1,2],
key2: [3,4],
key3: [5,6]
},
merged = Object.values(obj).flat()
console.log(merged)
.as-console-wrapper{min-height:100%}
If being unlucky enough to deal with IE or Edge, one may fallback to reduce()
for flattening:
const obj = {
key1: [1,2],
key2: [3,4],
key3: [5,6]
},
merged = Object.keys(obj).reduce(function(r,k){
return r.concat(obj[k])
}, [])
console.log(merged)
.as-console-wrapper{min-height:100%}
Upvotes: 9
Reputation: 1134
If you assume all the values of the object will an array you can make a Object.values()
loop and concat each array.
const obj={
'key1': [1,2],
'key2': [3,4],
'key3': [5,6],
};
const res = [];
for (const value of Object.values(obj)) {
res.push(...value);
}
/// res: [1,2,3,4,5,6]
Upvotes: 2
Reputation: 28750
var obj={ 'key1': [1,2], 'key2': [3,4], 'key3': [5,6] };
var result = Object.values(obj)
.reduce((accum, values) => {
accum.push(...values);
return accum;
}, []);
console.log(result);
Upvotes: 4