如何合并javascript两个对象但只更新更改的属性 [英] How can I merge javascript two objects but only update properties that change
问题描述
我正在尝试编写一个函数,让我在下面的示例中更新我的 kitchen
.然而,使用下划线的 extend
之类的东西会在更新整个 fridge
对象时吹走我冰箱里的啤酒.
I'm trying to write a function that will let me update my kitchen
in this example below. Using something like underscore's extend
, however, blows away the beer in my fridge as it's updating the entire fridge
object.
是否有一种简单的方法可以使用,以便我只更新 changeKitchen
对象中发生变化的属性,而不更新整个 fridge
对象?>
Is there a simple method I can use so that I only make updates with the properties that change in my changeKitchen
object and not update the entire fridge
object?
// 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 = _.extend(kitchen, changeKitchen);
console.log(updatedKitchen);
退货
var kitchen = {
fridge: {
celery: false // beer is gone
},
cabinets: {
candy: true
}
};
但是我想要:
var kitchen = {
fridge: {
beer: true,
celery: true // changed
},
cabinets: {
candy: true
}
};
推荐答案
既然你已经在使用 Underscore,你可以使用 Lodash 相反,它是 Underscore 的超集,并使用其 #merge
函数.
Since you're already using Underscore, you could use Lodash instead, which is a superset of Underscore, and use its #merge
function.
请参阅关于Lodash 和下划线之间的差异
// 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>
这篇关于如何合并javascript两个对象但只更新更改的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!