Object.assign 深层次合并

xiaoxiao2021-02-28  97

Object.assign 只能进行第一级层次的拷贝 如下代码:

var a = {b: {x: 1, z: 3}} var b = {b: {x: 1, y: 2}} console.log(Object.assign(a, b))

将得到 { b: { x: 1, y: 2 } } 期望得到 { b: { x: 1,z:3, y: 2 } }

此时需要使用到 lodash的merge方法 可以得到期望值:{ b: { x: 1, z: 3, y: 2 } }

var _ = require("lodash"); var a = {b: {x: 1, z: 3}} var b = {b: {x: 1, y: 2}} console.log(_.merge(a, b)); console.log(a);

注意: 这个方法会改变a的值

参考文档:https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge https://lodash.com/docs/4.17.4#merge

转载请注明原文地址: https://www.6miu.com/read-57732.html

最新回复(0)