简体   繁体   English

javascript中的深度和浅层合并

[英]Deep and shallow merge in javascript

What is the difference between deep and shallow merge of objects in javascript? javascript中对象的深度和浅度合并有什么区别? As far as I understand, deep merge recursively copies all the source object enumerable properties into target object. 据我所知,深度合并递归地将所有源对象可枚举属性复制到目标对象中。 But what does shallow merge do? 但浅合并有什么作用?

In a shallow merge, the properties of the first object are overwritten with the same property values of the second object. 在浅合并中,第一个对象的属性将被第二个对象的相同属性值覆盖。

Lets look at an example. 让我们看一个例子。 Setup: 建立:

var obj1 = {
  foo: {
    prop1: 42,
  },
};

var obj2 = {
  foo: {
    prop2: 21,
  },
  bar: {
    prop3: 10,
  },
};

Shallow: 浅:

var result = {
  foo: {          // `foo` got overwritten with the value of `obj2`
    prop2: 21,
  },
  bar: {
    prop3: 10,
  },
};

Deep: 深:

var result = {
  foo: {
    prop1: 42,
    prop2: 21,    // `obj2.foo` got merged into `obj1.foo`.
  },
  bar: {
    prop3: 10,
  },
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM