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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With