I want to merge one object (parent
) into another object (window
) without overwriting existing values.
The keys, values and length are not known of neither objects but i can safely assume that there will be nested objects.
I cannot re-create the target object because of reasons, it needs to be an actual merge.
What is the best way to do this in javascript?
Example:
var target = {
prop1: {
prop1stuff1: 42,
prop3: 15.5
},
42: 'stuff'
};
var source = {
prop1: {
prop1stuff1: 42,
prop4: 17,
prop3: 18
},
'42': 'test'
};
function merge(t, s){
//code to merge source (s) into target (t)
//without overwriting existing values
//and without overwriting t with a new object
}
merge(target, source); //alter target by reference, does not return anything
console.log(target);
// ^ this outputs:
{
prop1: {
prop1stuff1: 42,
prop3: 15.5,
prop4: 17
},
42: 'stuff'
}
Edit:
I can't assign a new object to target, i must add the properties one by one.
I also don't know how deep the nested objects will go
*Second Edit:***
TJ Crowder's answer works but the objects i tried to merge contain a lot of circular references, causing infinite loops.
I added a circular reference detector and i am now going to update TJ Crowder's answer.