简体   繁体   中英

How to merge two Javascript objects by key value

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
        }
    }
]

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);
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]));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM