连接对象值

时间:2015-02-12 09:42:30

标签: javascript arrays object concat

我有一个JavaScript对象,我确定任何键的值都是一个数组(在某些情况下甚至是空的):

{key1:["a","b","c"],key2:["d","e","f"],key3:...}

除了使用Underscore之外,有没有办法连接这个Object的所有值(并创建一个新数组)?

目前我使用Object.keys获取密钥名称,然后循环并连接。

感谢任何帮助。

4 个答案:

答案 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:

http://jsfiddle.net/qpLq11ea/

答案 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()将它们合并 spreadingArray.concat()中,就像这样:

const _obj = { key1:["a","b","c"], key2:["d","e","f"], key3:["g","h","i"] }

const _arr = [].concat(...Object.values(_obj))

console.log(_arr)


reducingObject.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)


要完成此操作,您还可以在concatenate的每个值上使用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)

希望这种方法可以帮助某人:)