Deep and shallow merge in javascript

前端 未结 1 1363
[愿得一人]
[愿得一人] 2021-02-02 10:19

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

1条回答
  •  隐瞒了意图╮
    2021-02-02 11:04

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

    0 讨论(0)
提交回复
热议问题