Reputation: 11
I need to merge two Javascript objects by its key value mapping.
Here is my first Javascript object
var json1= [
{ ID: 1, limit: 5, name: "foo" },
{ ID: 2, limit: 9, name: "dog" }
];
Here is my second Javascript object
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
[
{
{
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: 1,
LastRunTime: "January",
limit: 5,
name: "foo",
validate: true
},
{
ID: 2,
LastRunTime: "February",
limit: 9,
name: "dog",
validate: false
}
}
]
Upvotes: 0
Views: 2038
Reputation: 780724
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]));
}
}
Upvotes: 0
Reputation: 802
You need to switch the data representation. The best will be to store your json as:
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);
Upvotes: 2