我有一个JavaScript对象,我确定任何键的值都是一个数组(在某些情况下甚至是空的):
{key1:["a","b","c"],key2:["d","e","f"],key3:...}
除了使用Underscore之外,有没有办法连接这个Object的所有值(并创建一个新数组)?
目前我使用Object.keys
获取密钥名称,然后循环并连接。
感谢任何帮助。
答案 0 :(得分:8)
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"]
答案 1 :(得分:2)
检查array concat功能
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:
答案 2 :(得分:1)
试试这个: 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);
答案 3 :(得分:1)
Object.values()
和concatenate和[].concat.apply()
来获取值:
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()
将它们合并 spreading到Array.concat()
中,就像这样:
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()
的每个值,您可以获得相同的结果:
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()
。请记住:并非所有浏览器都支持它。
const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }
const _arr = Object.values(_obj).flat()
console.log(_arr)
希望这种方法可以帮助某人:)