如何在忽略空值的同时扩展对象? [英] How to extend an object while ignoring null values?

查看:90
本文介绍了如何在忽略空值的同时扩展对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说我有一个对象

var user = { 
    "Name": "Dan", 
    "Age": 27, 
    "Hobbies": null 
};

我想合并到以下基础对象上,以便我的用户对象具备所有必需的属性

which I would like to merge onto the following base object so that my user object will have all the required properties

var base = { 
    "Name": null, 
    "Height": null, 
    "Age": null, 
    "Hobbies": [
        { "Name": "Tennis", "Location": null },
        { "Name": "Football", "Location": null },
        { "Name": "Rugby", "Location": null }
    ]
};

合并到两个对象的最简单方法是使用用户对象扩展基础对象遵循

The easiest way to merge to the two objects would be to extend the base object with the user object as follows

$.extend(true, base, user);

这会将基础对象修改为

{ 
    "Name": "Dan", 
    "Height": null, 
    "Age": 27, 
    "Hobbies": null
};

我的问题是如何让extend方法不覆盖空值?例如,在这个例子中,如果用户爱好列表为空,我怎么还能获得爱好列表所以我最终得到以下

My question would be how can I get the extend method to not override null values? For example, in this instance, how can I still obtain a list of hobbies if the users hobby list is null so I end up with the following

{ 
    "Name": "Dan", 
    "Height": null, 
    "Age": 27, 
    "Hobbies": [
        { "Name": "Tennis", "Location": null },
        { "Name": "Football", "Location": null },
        { "Name": "Rugby", "Location": null }
    ]
};


推荐答案

您可以使用 undefined 作为值, jQuery.extend 将忽略。

You may use undefined as value which will be ignored by jQuery.extend.

var user = { "Name": "Dan", 
             "Age:" 27, 
             "Hobbies": undefined 
           };
$.extend(true, base, user);

这篇关于如何在忽略空值的同时扩展对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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