用另一个对象深层replace一个对象中的值 – javascript
嗨,我正在使用javascript / node.js。 我有两个数据对象。 (请注意,真正的对象比这个复杂得多。)
const original = { 'totAmount': 10, 'testVal': 'zzzzzzzz', 'potentialPaid': 10, 'depositAmount': 10, 'payment': { 'amount': 10, 'testVal': 'zzzzzzzz', 'details': { 'amount': 10, 'testVal': 'zzzzzzzz', 'statusHistory': { 'amount': 10, 'testVal': 'zzzzzzzz' } } }, 'coupon': {'test': 1000} };
和
const dataToUpdate = { 'totAmount': 65, 'potentialPaid': 65, 'depositAmount': 65, 'payment': { 'amount': 65, 'details': { 'amount': 65, 'statusHistory': { 'amount': 65 } } }, 'coupon': {} };
我想用相同的键replaceoriginal
的dataToUpdate
所有值。
我的预期结果是
const original = { 'totAmount': 65, 'testVal': 'zzzzzzzz', 'potentialPaid': 65, 'depositAmount': 65, 'payment': { 'amount': 65, 'testVal': 'zzzzzzzz', 'details': { 'amount': 65, 'testVal': 'zzzzzzzz', 'statusHistory': { 'amount': 65, 'testVal': 'zzzzzzzzz } } }, 'coupon': {} };
- 原始对象中所有具有相同键的值都应该被其他对象值replace。
我正在寻找各种解决scheme,如.merge
中的Object.assign()
. lodash
等等。
我坚持了这个超过3个小时,现在仍然没有find任何解决scheme。
有没有可用的默认JavaScriptfunction做这种事情? , 请帮忙。
提前致谢 。
经过一番研究,我发现从版本4.0.0开始, lodash有一个mergeWith函数,可以让你为合并应用一个自定义标准。
我在这里添加一个适合你的例子的jsfiddle,但是可能需要稍微调整一下,以覆盖其他一些场景(虽然我不确定)。
jsfiddle让你自定义合并标准的function是这样的:
function customizer(objValue, srcValue) { if (_.isEmpty(srcValue)) { return srcValue; } else { _.merge(objValue, srcValue); } }
这里是jsfiddle:
我希望这有帮助。
Lodash的_.mergeWith()
是recursion的。 _.mergeWith()
接受一个定制函数。 如果定制程序返回undefined
, _.mergeWith()
使用它的默认合并规则。
const original = {"totAmount":10,"testVal":"zzzzzzzz","potentialPaid":10,"depositAmount":10,"payment":{"amount":10,"testVal":"zzzzzzzz","details":{"amount":10,"testVal":"zzzzzzzz","statusHistory":{"amount":10,"testVal":"zzzzzzzz"}}},"coupon":{"test":1000}}; const dataToUpdate = {"totAmount":65,"potentialPaid":65,"depositAmount":65,"payment":{"amount":65,"details":{"amount":65,"statusHistory":{"amount":65}}},"coupon":{}}; const result = _.mergeWith(original, dataToUpdate, (objValue, srcValue) => _.isEmpty(srcValue) ? srcValue : undefined); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>