所以这是交易。我有一个包含一堆看起来像这样的对象的数组:
[{
"this": 5,
"that": 300,
"those": 15
},
{
"this": 6,
"that": 301,
"those": 16
},
{
"this": 7,
"that: 302,
"those": 17
}]
我想要的是一个物体,看起来像这样:
{
"this": [5, 6, 7],
"that": [300, 301, 302],
"those": [15, 16, 17]
}
我真的不知道该怎么称呼它,通过我搜索的内容,我找不到任何可以帮助我的类似内容。
答案 0 :(得分:2)
试试这个:
var a = [{
"this": 5,
"that": 300,
"those": 15
},{
"this": 6,
"that": 301,
"those": 16
},{
"this": 7,
"that": 302,
"those": 17
}];
a = a.reduce(
function(obj, item){ // Map the item to the object.
obj.this.push(item.this);
obj.that.push(item.that);
obj.those.push(item.those);
return obj;
},
{"this":[],"that":[],"those":[]} // Default (empty) object.
);
答案 1 :(得分:1)
对于较旧的浏览器(即IE8),reduce
不可用。如果您仍想支持这些,可以尝试:
var arr = [{
"this": 5,
"that": 300,
"those": 15
}, {
"this": 6,
"that": 301,
"those": 16
}, {
"this": 7,
"that": 302,
"those": 17
}];
var result = {};
for (var i = 0; i < arr.length; i++) {
for (var x in arr[i]) {
if (!result[x]) {
result[x] = [];
}
result[x].push(arr[i][x]);
}
}
console.log(result);
编辑:这也将允许修改源数组而不更改转换代码。
答案 2 :(得分:0)
[{"this": 5, "that": 300, "those": 15}, {"this": 6, "that": 301, "those": 16 }, {"this": 7, "that": 302, "those": 17}]
.reduce(function(prev, curr) {
return {
"this": [].concat(prev["this"], [curr["this"]]),
"that": [].concat(prev["that"], [curr["that"]]),
"those": [].concat(prev["those"], [curr["those"]]),
};
})
结果:
{"this":[5,6,7],"that":[300,301,302],"those":[15,16,17]}
自己在控制台中测试。
使用concat
我们不必传递空的{"this":[],"that":[],"those":[]}
初始值。
[{"this": 5, "that": 300, "those": 15}, {"this": 6, "that": 301, "those": 16 }, {"this": 7, "that": 302, "those": 17}]
.reduce(function(prev, curr) {
for (var key in prev) {
prev[key] = [].concat(prev[key], curr[key])
}
return prev;
})
正如您所看到的,此版本不对关键名称做任何假设。