Lodash 合并:仅在源值与目标值匹配时复制对象属性
Posted
技术标签:
【中文标题】Lodash 合并:仅在源值与目标值匹配时复制对象属性【英文标题】:Lodash merge: only copy object properties if source value matches destination value 【发布时间】:2020-01-14 20:39:05 【问题描述】:我有两个深度/复杂的对象被合并在一起。在“地址”数组中,需要有两个对象用于两种不同的地址类型,“PRIMARY”和“MAILING”。
在我的目标对象中,“PRIMARY”obj 位于“MAILING”obj 之上。一切都很好,除了源对象中只有一个“MAILING”obj 可用。发生这种情况时,两个对象的“addressType”属性都被“MAILING”覆盖
// In destination obj:
addresses: [
addressType: "PRIMARY",
addressLine1: "",
addressLine2: "",
city: "",
state: "",
zip: ""
,
addressType: "MAILING",
...
]
// In source obj:
addresses: [
addressType: "MAILING",
addressLine1: "123 Main St",
addressLine2: "",
city: "Hawkins",
state: "IN",
zip: "46001"
]
merge
之后/当前输出(重复地址类型):
_.merge(, destination, source); //need new object
addresses: [
addressType: "MAILING",
addressLine1: "123 Main St",
addressLine2: "",
city: "Hawkins",
state: "IN",
zip: "46001"
,
addressType: "MAILING",
addressLine1: "",
addressLine2: "",
city: "",
state: "",
zip: ""
]
期望的输出:
// DESIRED OUTPUT:
addresses: [
addressType: "PRIMARY",
addressLine1: "",
addressLine2: "",
city: "",
state: "",
zip: ""
,
addressType: "MAILING",
addressLine1: "123 Main St",
addressLine2: "",
city: "Hawkins",
state: "IN",
zip: "46001"
]
来自源的地址数组可能不包含任何对象,也可能不包含任何对象,也可能不包含一个对象。
所以我的问题是,如果源 obj 中只有“MAILING”,我如何防止它覆盖“PRIMARY”obj,留下“MAILING”(来自源)和“PRIMARY” " obj(来自目的地)?
我应该改用 mergeWith 吗?
【问题讨论】:
你能写出你有什么数组吗? @StepUp - 添加了合并后的当前输出。 【参考方案1】:我能够使用以下定制器功能以及mergeWith
使每个场景都正常工作:
mergeWith(, destination, source, customizer);
const customizer = (objValue, srcValue, key) =>
if (key === "addresses")
let merged = merge(
keyBy(objValue, "addressType"),
keyBy(srcValue, "addressType")
);
let value = values(merged);
return value;
;
【讨论】:
以上是关于Lodash 合并:仅在源值与目标值匹配时复制对象属性的主要内容,如果未能解决你的问题,请参考以下文章