I am currently working on a project and I've written something that will do for what I'm trying to do but isn't perfect. It currently takes in 2 objects and merges them letting the second override the first if there is a property name conflict.
The code looks like this.
function appendObject(start, obj) {
var newObject = start;
for (var propName in obj) {
if (typeof start[propName] === "object" && typeof obj[propName] === "object") {
for (var propName2 in obj[propName]) {
newObject[propName][propName2] = obj[propName][propName2];
}
} else {
newObject[propName] = obj[propName];
}
}
return newObject;
}
This will go one layer deep. So if there is a flat object as a property it will still be able to handle it. But what if there is a more complex object as a property in this object? I have not been able to figure out a good way to handle any level of complexity.
Perhaps I'm missing something basic and there is an easier way to merge objects like this. The practical application here is we have a 'default' set of properties we need on the json and then some possible initial values and user inputted values.
Any ideas?