如何合并嵌套对象Javascript? [复制]
Posted
技术标签:
【中文标题】如何合并嵌套对象Javascript? [复制]【英文标题】:How to merge nested objects Javascript? [duplicate] 【发布时间】:2020-06-23 12:08:53 【问题描述】:let x = "1": "id": 1 , "2": "id": 1, "key": "value"
let y = "2": "id": 2
let z =
...x,
...y,
console.log(z);
我想要输出
"1": "id": 1 , "2": "id": 2, "key": "value"
当前输出为
"1": "id": 1 , "2": "id": 2
【问题讨论】:
【参考方案1】:键只会应用到第一级,你必须下一级。
let x = "1": "id": 1 , "2": "id": 1, "key": "value"
let y = "2": "id": 2
let z = ...x, ...y // outer
for (let k in z) z[k] = ...x[k], ...y[k] // inner
console.log(z)
.as-console-wrapper top: 0; max-height: 100% !important;
<!-- Expected
"1":
"id": 1
,
"2":
"id": 2,
"key": "value"
-->
更稳健的方法
我借用 Lewis 的示例来深度合并多个对象并将其转换为插件。
// Based on: https://***.com/a/55736757/1762224
const ObjectUtils = (() =>
const keys, freeze = Object // sym-links
let __isObject, __merge, __coalesceByKey, __deepMerge // fwd declaration
__isObject = a => typeof a === "object" && !Array.isArray(a)
__merge = (a, b) =>
__isObject(a) && __isObject(b)
? __deepMerge(a, b)
: __isObject(a) && !__isObject(b)
? a : b
__coalesceByKey = src => (acc, key) =>
(acc[key] && src[key]
? (acc[key] = __merge(acc[key], src[key]))
: (acc[key] = src[key])) && acc
__deepMerge = (target, ...sources) =>
sources.reduce(
(acc, src) => keys(src).reduce(__coalesceByKey(src), acc), target
)
return freeze( isObject : __isObject, deepMerge : __deepMerge )
)()
let x = "1": "id": 1 , "2": "id": 1, "key": "value"
let y = "2": "id": 2
console.log(ObjectUtils.deepMerge(, x, y));
.as-console-wrapper top: 0; max-height: 100% !important;
【讨论】:
【参考方案2】:这是我的解决方案:
let x = "1": id: 1 , "2": id: 1, key: "value" ;
let y = "2": id: 2 ;
let z = ;
for (let [key, value] of Object.entries(x))
if (y.hasOwnProperty(key))
z[key] =
...value,
id: y[key].id
;
else
z[key] = value;
console.log(z);
【讨论】:
【参考方案3】:我会使用 lodash:
_.merge(object, [sources])
此方法类似于 _.assign ,不同之处在于它递归地将源对象的自己的和继承的可枚举字符串键控属性合并到目标对象中。如果存在目标值,则跳过解析为未定义的源属性。数组和普通对象属性递归合并。其他对象和值类型被赋值覆盖。源对象从左到右应用。后续来源会覆盖先前来源的属性分配。
【讨论】:
就像弗罗多说的,看看这个lodash.com/docs/4.17.15#merge。 _merge 和 _mergeWith以上是关于如何合并嵌套对象Javascript? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
检查 JavaScript 中是不是存在深度嵌套对象属性的最简单方法是啥? [复制]