有没有办法让$ .extend不会将null值属性传播到目标

时间:2014-05-07 20:23:45

标签: javascript jquery

这是执行代码行,其中设置了方法中的defaultOptions列表  除了少数例外之外,还有一堆空值......

var passedOptions = $.extend({},defaultOptions, configOptions);

defaultOptions =
{ 
    "method":"POST",
    "url":"",
    "params":null,
    "data":null,
    "headers":null,
    "xsrfHeaderName":null,
    "xsrfCookieName":null,
    "transformRequest":null,
    "transformResponse":null,
    "cache":false,
    "timeout":null,
    "withCredentials":false,
    "reqsponseType":null
}

configOptions = 
 {
    "url":"someurl/blahblah",
    "data": "username":"me@email.com",
    "email":"me@email.com"
 }

这就是我想要的passOptions看起来像

passOptions = 
{
   "method":"POST",
   "url":"someurl/blahblah",
   "data": "username":"me@email.com",
   "email":"me@email.com"
   "cache" : false,
   "withCredentials" : false
}

基本上是两者的组合,但是没有将具有空值的属性复制到目标。这可能吗?

2 个答案:

答案 0 :(得分:1)

你可以手动完成:

var passedOptions={};
for(var i in defaultOptions){
    if(defaultOptions[i] != null){
        passedOptions[i]=defaultOptions[i];
    }
}
for(var i in configOptions){
    if(configOptions[i] != null){
        passedOptions[i]=configOptions[i];
    }
}

答案 1 :(得分:0)

我找到了答案,虽然它没有忽略空值,但它允许将对象合并到目标,同时忽略具有未定义值的属性。用undefined替换所有空值。

How to extend an object while ignoring null values?