有谁知道我可以进一步浓缩我的mergePath方法,该方法基于键/值路径合并两个对象上的键?我下面的解决方案使用Lodash。
let obj1 = { z: {fields: { a: "200", b: "2" }}}
let obj2 = { z: {fields: { a: "2", b: "20" }}}
let objsPath = "z.fields"
let mergePath = (objsPath, obj1, obj2) => (
_.set(obj1, objsPath, {..._.get(obj1, objsPath), ..._.get(obj2, objsPath)})
)
最佳答案
您可以使用_.merge()
将路径从obj2
复制到obj2
。然后,您可以返回obj1
(我用过comma operator):
const obj1 = { z: {fields: { a: "200", b: "2" }}}
const obj2 = { z: {fields: { a: "2", b: "20" }}}
const objsPath = "z.fields"
const mergePath = (objsPath, obj1, obj2) => (
_.merge(_.get(obj1, objsPath), _.get(obj2, objsPath)), obj1
)
console.log(mergePath(objsPath, obj1, obj2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
关于javascript - 基于路径合并JavaScript对象的最短方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50398794/