问题
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.
回答1:
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"]
回答2:
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:
http://jsfiddle.net/qpLq11ea/
回答3:
A simple approach is to get the values using 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)
Another similar way, is to merge 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)
Also reducing each value of the 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)
To finish, you can also use 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 :)
回答4:
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);
来源:https://stackoverflow.com/questions/28474049/concatenate-object-values