Reputation:
I have a JavaScript Object and I'm sure the value of any key is an array (even empty in some case):
{key1:["a","b","c"],key2:["d","e","f"],key3:...}
Aside from using Underscore, is there any way to concatenate all the values of this Object (and create a new array)?
At the moment I get the keys name using Object.keys
, then I loop and concatenate.
Any help is appreciated.
Upvotes: 9
Views: 32251
Reputation: 3927
Object.values()
and concatenate them with [].concat.apply()
in this way:const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = [].concat.apply([], Object.values(_obj))
console.log(_arr)
Object.values()
by spreading them into Array.concat()
like this:const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = [].concat(...Object.values(_obj))
console.log(_arr)
Object.values()
and concatenate them, you can get the same result:const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = Object.values(_obj).reduce((r,c) => r.concat(c), [])
console.log(_arr)
Array.prototype.flat()
over each value of the Object.values()
. Just keep in mind: it's not supported on all browsers.const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = Object.values(_obj).flat()
console.log(_arr)
Hope this methods could help someone out there :)
Upvotes: 14
Reputation: 415
var obj = {key1:["a","b","c"],key2:["d","e","f"]};
var arr = Object.keys(obj).reduce(function(res, v) {
return res.concat(obj[v]);
}, []);
// ["a", "b", "c", "d", "e", "f"]
Upvotes: 13
Reputation: 1442
Try this: http://jsfiddle.net/6hbp5bzo/
var arr= [];
var o={key1:["a","b","c"],key2:["d","e","f"]}
for(key in o){
if(o.hasOwnProperty(key)){
arr.push(o[key]);
}
}
alert(arr);
Upvotes: 1
Reputation: 7488
Check the array concat function
var obj = {key1:["a","b","c"],key2:["d","e","f"],key3:["g","h"]};
var resultArray = [];
for (var key in obj) resultArray = resultArray.concat(obj[key]);
alert(resultArray);
jsfiddle:
Upvotes: 2