Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript loop through object and insert missing keys even in children

I need to synch two javascript objects I would like to fill object2 with the missing keys from object1 without replacing the existing ones, even for the nested ones:

var object1 = {
    firstName: "Marco",
    lastName: "Rossi",
    favoriteFood: {firstCourse: "pasta", secondCourse: "salsiccia"},
    favoriteDrink: "Vino",
    favoriteSong: "O sole mio"
}

var object2 = {
    firstName: "Marco",
    lastName: "Rossi",
    favoriteFood: {firstCourse: "pasta"},
    favoriteSong: "Viaggiare"
}

I don't really know how to go into the nested keys. Especially to keep checking for inner nests, what if you have 5 nests down or something like that I know how do deal with the first level but not further down.

The desired result for objec2 would be

var object2 = {
    firstName: "Marco",
    lastName: "Rossi",
    favoriteFood: {firstCourse: "pasta", secondCourse: "salsiccia"},
    favoriteDrink: "Vino",
    favoriteSong: "Viaggiare"
}

Thanks in advance for your help.

like image 343
Leonardo Amigoni Avatar asked Oct 21 '25 16:10

Leonardo Amigoni


1 Answers

You need to write recursive function to handle nested objects. Maybe something like this:

var object1 = {
    firstName: "Marco",
    lastName: "Rossi",
    favoriteFood: {firstCourse: "pasta", secondCourse: "salsiccia"},
    favoriteMovie: {rating: 7, title: "Monday"},
    favoriteDrink: "Vino",
    favoriteSong: "O sole mio"
}

var object2 = {
    firstName: "Marco",
    lastName: "Rossi",
    favoriteFood: {firstCourse: "pasta"},
    favoriteSong: "Viaggiare"
}

function fillObject(from, to) {
    for (var key in from) {
        if (from.hasOwnProperty(key)) {
            if (Object.prototype.toString.call(from[key]) === '[object Object]') {
                if (!to.hasOwnProperty(key)) {
                    to[key] = {};
                }
                fillObject(from[key], to[key]);
            }
            else if (!to.hasOwnProperty(key)) {
                to[key] = from[key];
            }
        }
    }
}

fillObject(object1, object2);

alert( JSON.stringify(object2, null, '    ') );

Note: if you wonder about this line Object.prototype.toString.call(from[key]) - this is to reliably check that value is an object, because typeof null also reports object.

like image 86
dfsq Avatar answered Oct 23 '25 07:10

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!