Deep and shallow merge in javascript

梦想与她 提交于 2019-12-20 09:55:49

问题


What is the difference between deep and shallow merge of objects in 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?


回答1:


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,
  },
};


来源:https://stackoverflow.com/questions/42731453/deep-and-shallow-merge-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!