我需要通过其键值映射合并两个Javascript对象。
这是我的第一个Javascript对象
var json1= [
{ ID: 1, limit: 5, name: "foo" },
{ ID: 2, limit: 9, name: "dog" }
];
这是我的第二个Javascript对象
var json2 = [
{ ID: 2, validate: false, LastRunTime: "February" },
{ ID: 1, validate: true, LastRunTime: "January" }
];
$.extend(true, {}, json1, json2);
这给了我这样的Javascript
[
{
{
ID: 2,
LastRunTime: "February",
limit: 5,
name: "foo",
validate: false
},
{
ID: 1,
LastRunTime: "January",
limit: 9,
name: "dog",
validate: true
}
}
]
但是我正在寻找将ID映射为键的代码,然后合并这样的Javascript对象而不管它们在数组中的顺序。
[
{
{
ID: 1,
LastRunTime: "January",
limit: 5,
name: "foo",
validate: true
},
{
ID: 2,
LastRunTime: "February",
limit: 9,
name: "dog",
validate: false
}
}
]
答案 0 :(得分:2)
您需要切换数据表示。最好的方法是将你的json存储为:
var json1 = {
"1": { ID: 1, limit: 5, name: "foo" },
"2": { ID: 2, limit: 9, name: "dog" }
};
如果不可能,那么您可以动态转换数据:
var json1obj = {};
json1.forEach(function(obj) {
json1obj[obj.ID] = obj;
});
var json2obj = ...;
$.extend(true, {}, json1obj, json2obj);
答案 1 :(得分:0)
var result = [];
for (var i = 0; i < json1.length; i++) {
var found = false;
for (var j = 0; j < json2.length; j++) {
if (json1[i].ID == json2[j].ID) {
result.push($.extend(true, {}, json1[i], json2[j]));
found = true;
break;
}
}
if (!found) {
// If no match found in json2, put a copy in the result
result.push($.extend(true, {}, json1[i]));
}
}