Javascript 将多个对象转换为一个具有与数组相同的键、值的对象
这就是交易。我有一个数组,其中包含一堆看起来像这样的对象:Javascript 将多个对象转换为一个具有与数组相同的键、值的对象,javascript,arrays,object,Javascript,Arrays,Object,这就是交易。我有一个数组,其中包含一堆看起来像这样的对象: [{ "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] }
[{
"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]
}
我想要的是一个物体,看起来像这样:
[{
"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]
}
我真的不知道该怎么称呼它,根据我的搜索,我找不到任何类似的东西可以帮助我。试试这个:
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.
);
这将使用。对于较旧的浏览器(即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);
var-arr=[{
"这":五,,
“那”:300,
“那些”:15
}, {
"这":6,,
“那”:301,
“那些”:16
}, {
"这":7,,
“那”:302,
“那些”:17
}];
var result={};
对于(变量i=0;i
编辑:这还允许在不更改转换代码的情况下修改源数组。Fancy reduce+concat variation
结果:
{"this":[5,6,7],"that":[300,301,302],"those":[15,16,17]}
自己在控制台中测试
通过使用concat
我们不必传递空的{“this”:[],“that”:[],“that”:[],“thats”:[]}
初始值
版本#2。通用代码
正如您所看到的,这个版本没有对键名做任何假设。我将其称为将数组从行/列转换到列/行。对于这两个建议的答案。Chrome中的双for循环速度更快。您忘记为新数组指定
a
引用。可以将其分配给新变量ofc。谢谢。:)我也做了一个,但忘了保存。还添加了两个建议答案中的一个。这太棒了!我选择这个是因为它在任何地方都能工作,没有任何特殊需要。