最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angularjs merge two objects ignoring null and missing values - Stack Overflow

programmeradmin0浏览0评论

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 (object 2 overrides object 1 except for null properties or properties he doesn't have) :

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

angular.extend(object1, object2) works but overrides age property to null

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 (object 2 overrides object 1 except for null properties or properties he doesn't have) :

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

angular.extend(object1, object2) works but overrides age property to null

Share Improve this question asked Feb 12, 2015 at 9:34 TrtGTrtG 2,8487 gold badges29 silver badges39 bronze badges 1
  • that you have to remove manually – Ankush Jain Commented Feb 12, 2015 at 9:36
Add a comment  | 

2 Answers 2

Reset to default 12

You can remove the null properties in object 2 before calling the extend.

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>

You can use this function as custom extend mechanism instead of native 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;
发布评论

评论列表(0)

  1. 暂无评论