Since you're already using Underscore, you could use Lodash instead, which is a superset of Underscore, and use its #merge
function.
See this question about Differences between Lodash and underscore
// My original kitchen
var kitchen = {
fridge: {
beer: true,
celery: false
},
cabinets: {
candy: true
}
};
// updates I would like to make to my kitchen
var changeKitchen = {
fridge: {
celery: true
}
};
var updatedKitchen = _.merge(kitchen, changeKitchen);
document.write(JSON.stringify(updatedKitchen));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
Use _.extend
on the nested objects instead:
function update(obj1, obj2) {
for (var p in obj2) {
if (obj1[p]) {
_.extend(obj1[p], obj2[p]);
} else {
obj1[p] = obj2[p];
}
}
}
update(kitchen, changeKitchen);
Here is a solution in plain Javascript:
var kitchen = { fridge: { beer: true, celery: false }, cabinets: { candy: true } },
changeKitchen = { fridge: { celery: true } };
function update(source, target) {
Object.keys(target).forEach(function (k) {
if (typeof target[k] === 'object') {
source[k] = source[k] || {};
update(source[k], target[k]);
} else {
source[k] = target[k];
}
});
}
update(kitchen, changeKitchen);
document.write('<pre>' + JSON.stringify(kitchen, 0, 4) + '</pre>');
Using setInterval or RequestAnimationFrame, I'd like to get the progression value from lerping between X and Y. Assuming that X is 0 and Y is 1, I want to have 0 when it starts, 0.5 in the half, and 1 ...
Using setInterval or RequestAnimationFrame, I'd like to get the progression value from lerping between X and Y. Assuming that X is 0 and Y is 1, I want to have 0 when it starts, 0.5 in the half, and 1 ...
I am creating context menu based on javascript array with callback functions but getting two issues unable to hide submenu when mouse moves to an element with no children nodes(On Delete Section). ...
I am creating context menu based on javascript array with callback functions but getting two issues unable to hide submenu when mouse moves to an element with no children nodes(On Delete Section). ...
I have many elements with same name: <input type="text" name="Education[GraduationDate][0]" /> <input type="text" name="Education[GraduationDate][1]" /> <input type="text" name="...
I have many elements with same name: <input type="text" name="Education[GraduationDate][0]" /> <input type="text" name="Education[GraduationDate][1]" /> <input type="text" name="...
I'm currently using the command: $ ember build --watch --output-path=../public/ to build my ember app. Any ways of achieving the same thing but with a livereload? Thank you.
I'm currently using the command: $ ember build --watch --output-path=../public/ to build my ember app. Any ways of achieving the same thing but with a livereload? Thank you.