How can I loop nested objects if I don't know how much children they have?
For instance, if I wanted to update an old object with another object (code sample), I'll need to go through every node in the objects, to check the keys/values match, one by one.
var savedData = {
"a": {
"x": {
"foo": 1,
"foofoo": 11
},
"y": {
"bar": 2,
"barbar": 22
}
},
"b": {
//...
},
"c": {
//...
}
};
var newData = {
"a": {
"x": {
"foo": 7 //<== new value to be changed;
//<== notice there were "foofoo" key here, we need to keep this key and does NOT remove it;
},
"y": {
"bar": 8 //<== new value to be changed;
//<== notice there were "barbar" key here, we need to keep this key and does NOT remove it;
},
"z": { //<== this is a brand new child object to be added to the savedData;
"baz": 9
}
}
};
updateSavedData(newData);
function updateSavedData(newData) {
if (savedData) {
Object.keys(savedData).forEach(function(savedKeyLevel1) {
Object.keys(newData).forEach(function(newKeyLevel1) {
if (savedKeyLevel1 === newKeyLevel1) {
console.log('the key [' + savedKeyLevel1 + '] exist among the saved and the new data!');
if (jQuery.type(savedData[savedKeyLevel1]) === "object") {
console.log('the key [' + savedKeyLevel1 + '] is an object!');
//start looping again, but this time in a deeper level of this child object...
Object.keys(savedData[savedKeyLevel1]).forEach(function(savedKeyLevel2) {
Object.keys(newData[newKeyLevel1]).forEach(function(newKeyLevel2) {
if (savedKeyLevel2 === newKeyLevel2) {
console.log('the key [' + savedKeyLevel1 + ' -> ' + savedKeyLevel2 + '] exist among the saved and the new data!');
//...
//<== my question is about what to do here?
//if I don't know how much deeper the savedData is.
} else {
//this is a brand new child object, add it to the tree;
savedData[savedKeyLevel1][newKeyLevel2] = newData[newKeyLevel1][newKeyLevel2];
}
});
});
}
} else {
//this is a brand new child object, add it to the tree;
savedData[newKeyLevel1] = newData[newKeyLevel1];
}
});
});
} else {
savedData = newData;
}
console.log('The savedData after update is:\n', JSON.stringify(savedData));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My question is:
What if I don't know how much deeper the objects are?
What am I looking for here to read/try?