[英]Transform multiple objects into one object with same key, value as an array
所以這里是交易。 我有一個包含一堆看起來像這樣的對象的數組:
[{
"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);
編輯:這還將允許在不更改轉換代碼的情況下修改源數組。
[{"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;
})
如您所見,此版本不對鍵名進行任何假設。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.