Javascript 如何合并对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28473574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:50:02  来源:igfitidea点击:

How to merge objects?

javascriptangularjsmergejavascript-objectsextends

提问by TrtG

For instance, from these two objects :

例如,从这两个对象:

var object1 = {
  "color": "yellow",
  "size": null,
  "age": 7,
  "weight": null
}

var object2 = {
  "color": "blue",
  "size": 51,
  "age": null
}

I want this (object2overrides object1except for nullproperties or properties he doesn't have):

我想要这个(除了他没有的属性或属性之外的object2覆盖):object1null

{
  "color": "blue",
  "size": 51,
  "age": 7,
  "weight": null
}

回答by Beri

Copy

复制

var src = { name: 'Apple', price: 5};
var dst= angular.copy(src);
  • deep copy
  • 深拷贝

Extend:

扩展

var mergedObject = angular.extend(dst, src1, src2, ...) 
  • shallow copy
  • 浅拷贝

Merge:

合并

var mergedObject = angular.merge(dst, src);
  • since angular 1.4+
  • deep (recursively) copy
  • 自 Angular 1.4+
  • 深(递归)复制

If you want to not overwrite with null, you can use this.

如果你不想用 null 覆盖,你可以使用this



Object.assign():

Object.assign()

let movie2 = Object.assign({}, movie1, { episode: 8 });
  • fot Angular 2+ (ECMAScript 6)
  • Angular 2+ (ECMAScript 6)

Sources:

资料来源:

回答by Rafael P. Miranda

For newer versions (at least 1.4.0) of angular you can use angular.merge

对于较新版本(至少 1.4.0)的 angular,您可以使用 angular.merge

Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy.

与 extend() 不同,merge() 递归地下降到源对象的对象属性,执行深度复制。

回答by Saeed D.

Using angualr.extend will not produce the result requested. The object2.age null value will override object1.age value.

使用 angualr.extend 不会产生请求的结果。object2.age null 值将覆盖 object1.age 值。

angular.extend(object1, object2) will produce the following result:

angular.extend(object1, object2) 将产生以下结果:

{
    "color" : "blue", 
    "size" : 51, 
    "age" : null,   <=== undesirable result
    "weight" : null
}

Use the following code to skip over null properties

使用以下代码跳过空属性

for (var prop in object1) {
    if(object1.hasOwnProperty(prop) && object2.hasOwnProperty(prop) && object2[prop]!=null) {
        object1[prop] = object2[prop];
    }
}

This will produce the following requested result

这将产生以下请求的结果

{
    "color" : "blue", 
    "size" : 51, 
    "age" : 7, 
    "weight" : null
}