How to merge objects?

后端 未结 3 1529
一整个雨季
一整个雨季 2020-12-29 19:05

For instance, from these two objects :

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

var object2 = {
  \"col         


        
3条回答
  •  时光说笑
    2020-12-29 19:45

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

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

    {
        "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
    }
    

提交回复
热议问题