javascript中的深度合并 [英] Deep and shallow merge in javascript

查看:60
本文介绍了javascript中的深度合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javascript中对象的深层合并和浅层合并有什么区别?
据我了解,深度合并以递归方式将所有源对象的可枚举属性复制到目标对象中。但是浅层合并的作用是什么?

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?

推荐答案

在浅层合并中,第一个对象的属性被相同的属性值覆盖

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

浅:

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

深度:

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

这篇关于javascript中的深度合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆