[英]How to merge two Javascript objects by key value
I need to merge two Javascript objects by its key value mapping. 我需要通过其键值映射合并两个Javascript对象。
Here is my first Javascript object 这是我的第一个Javascript对象
var json1= [
{ ID: 1, limit: 5, name: "foo" },
{ ID: 2, limit: 9, name: "dog" }
];
Here is my second Javascript object 这是我的第二个Javascript对象
var json2 = [
{ ID: 2, validate: false, LastRunTime: "February" },
{ ID: 1, validate: true, LastRunTime: "January" }
];
$.extend(true, {}, json1, json2);
this gives me the resultant Javascript like this 这给了我这样的结果Javascript
[
{
{
ID: 2,
LastRunTime: "February",
limit: 5,
name: "foo",
validate: false
},
{
ID: 1,
LastRunTime: "January",
limit: 9,
name: "dog",
validate: true
}
}
]
but I am looking for the code that map ID as a key and then merge the Javascript objects like this irrespective of their order in array. 但我正在寻找将ID映射为键的代码,然后合并这样的Javascript对象,而不管它们在数组中的顺序如何。
[
{
{
ID: 1,
LastRunTime: "January",
limit: 5,
name: "foo",
validate: true
},
{
ID: 2,
LastRunTime: "February",
limit: 9,
name: "dog",
validate: false
}
}
]
You need to switch the data representation. 您需要切换数据表示。 The best will be to store your json as: 最好的方法是将你的json存储为:
var json1 = {
"1": { ID: 1, limit: 5, name: "foo" },
"2": { ID: 2, limit: 9, name: "dog" }
};
If it's impossible then you can convert your data on the fly: 如果不可能,那么您可以动态转换数据:
var json1obj = {};
json1.forEach(function(obj) {
json1obj[obj.ID] = obj;
});
var json2obj = ...;
$.extend(true, {}, json1obj, json2obj);
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]));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.