gpt4 book ai didi

Javascript仅将源的交集分配给目标对象

转载 作者:行者123 更新时间:2023-12-03 09:46:17 26 4
gpt4 key购买 nike

我有两个对象,我想从源更新目标对象值,但只更新目标中已经存在的值。

const target = {
a: 1,
b: 2,
c: {
c_a: 3,
c_b: 4,
}
}

const source = {
a: 10,
c: {
c_a: 30,
c_d: 50,
},
d: 60
}

const result = assignOnlyIntersection(target, source);

JSON.stringify(result)

// {
// a: 10,
// b: 2,
// c: {
// c_a: 30,
// c_b: 4
// }
// }

有没有好办法ES6 为了这?如果没有,lodash 是否有这方面的功能?如果不是,如何以一种好的方式解决它?

最佳答案

一个简单的递归函数可以:

function assignOnlyIntersection(target, source) {
if (Object(target) !== target || Object(source) !== source)
return source;
for (const p in source)
if (p in target)
target[p] = assignOnlyIntersection(target[p], source[p]);
return target;
}

关于Javascript仅将源的交集分配给目标对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com