Angularjs合并了两个忽略null和缺失值的对象

时间:2015-02-12 09:34:47

标签: javascript angularjs

例如,从这两个对象:

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

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

我想要这个(对象2覆盖对象1,除了null属性或他没有的属性):

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

angular.extend(object1,object2)有效,但会将age属性覆盖为null

2 个答案:

答案 0 :(得分:11)

您可以在调用extend之前删除对象2中的null属性。

var myApp = angular.module('myApp',[]);

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

var inside = {
    "name": "me",
    "age" : 9,
    "nothing": null
}

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

function removeNullIn(prop, obj)
{
  var pr = obj[prop];
  if(pr === null || pr === undefined) delete obj[prop]; 
  else if(typeof pr === 'object') for (var i in pr) removeNullIn(i, pr);
}

function removeNull(obj)
{
    for (var i in obj) {
        removeNullIn(i, obj);
    }
}

removeNull(object2);

var mergedObject = angular.extend(object1, object2);
console.log(mergedObject);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>

答案 1 :(得分:3)

您可以将此函数用作自定义扩展机制,而不是本机angular.extend。

/**
 * Extends dst with props from src
 * @see 
 *  customExtend({a: 1, test : 1}, {b: 1, test : 2});
 *  //this will return {a: 1, b: 1, test: 2}
 * @returns {Object}
 */
var customExtend = function (/* [emptyObject], dst, src */) {
    var $$args = Array.prototype.slice.call(arguments, 0);

    if ($$args.length === 3) {
        $$args.shift();
    }

    for (var i in $$args[1]) {
        if ($$args[1][i] !== null || angular.isUndefined($$args[1][i])) {
            $$args[0][i] = $$args[1][i];
        }
    }

    return $$args[0];
};


angular.customExtend = customExtend;