按键组合json数组,javascript [英] Combine json arrays by key, javascript
问题描述
我需要组合两个 json 数组,由两个 rest 服务提供.具有相同id"的条目属于一起.
I need to combine two json arrays, delivered by two rest services. The entries with the same "id" belong together.
json1 = [{id:1,name:'aaa'},
{id:5,name:'ccc'},
{id:3,name:'bbb'}
];
json2 = [{id:3,parameter1:'x', parameter2:'y', parameter3:'z'},
{id:1,parameter1:'u', parameter2:'v', parameter3:'w'},
{id:5,parameter1:'q', parameter2:'w', parameter3:'e'}
];
我需要通过以下方式在 javascript 中组合/复制/克隆 json 数组(我的模型在 angular2 中):
I need a combined/copied/cloned json array in javascript in the following way (my model in angular2):
json3 = [{id:3,name:'bbb',parameter1:'x', parameter2:'y', parameter3:'z'},
{id:1,name:'aaa', parameter1:'u', parameter2:'v', parameter3:'w'},
{id:5,name:'ccc', parameter1:'q', parameter2:'w', parameter3:'e'}
];
有没有办法将它们结合起来?参数名称没有准确定义,需要使用可变参数向量.
Is there a way to combine them? The parameter names are not defined exactly and it needs to work with variable parameter vectors.
我尝试了每个循环的混合.在我看来很丑.
I tried it with mixed for each loops. Seems to me very ugly.
推荐答案
如果你想编写它以便你可以接收任意数量的数组,而不是仅 2,您可以使用 参数,并做这样的事情:
If you wanted to write it so that you could take in any number of arrays, not just 2, you could utilize arguments, and do something like this:
var json1 = [{id:1,name:'aaa'},{id:5,name:'ccc'},{id:3,name:'bbb'}];
var json2 = [{id:3,parameter1:'x', parameter2:'y', parameter3:'z'},
{id:1,parameter1:'u', parameter2:'v', parameter3:'w'},
{id:5,parameter1:'q', parameter2:'w', parameter3:'e'}];
function joinObjects() {
var idMap = {};
// Iterate over arguments
for(var i = 0; i < arguments.length; i++) {
// Iterate over individual argument arrays (aka json1, json2)
for(var j = 0; j < arguments[i].length; j++) {
var currentID = arguments[i][j]['id'];
if(!idMap[currentID]) {
idMap[currentID] = {};
}
// Iterate over properties of objects in arrays (aka id, name, etc.)
for(key in arguments[i][j]) {
idMap[currentID][key] = arguments[i][j][key];
}
}
}
// push properties of idMap into an array
var newArray = [];
for(property in idMap) {
newArray.push(idMap[property]);
}
return newArray;
}
var json3 = joinObjects(json1, json2);
console.log(JSON.stringify(json3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于按键组合json数组,javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!