gpt4 book ai didi

javascript - Underscore JS 使用新对象的非空值扩展对象

转载 作者:行者123 更新时间:2023-11-30 17:40:14 25 4
gpt4 key购买 nike

我想做类似...

_.extend(original, fresh);

但只复制不为空的属性,所以...

var original = {a:1, b:2, c:3}
var fresh = {a:5, b:null}

var mixed = _.extend(original, fresh)
// currently mixed is {a:5,b:null,c:3}
// I want it to be {a:5,b:2,c:3}

更新

我取得了一些进展,但它不适用于嵌套对象...

http://jsfiddle.net/billymoon/2GwMx/1/

var original = {a:1, b:2, c:3, d:{g:1}}
var fresh = {a:5, b:null,c:"", d:{e:4,f:5,g:null}}

var mixed = _.extend( original, _.reduce(fresh,function(a,v,k){
if(v){ a[k]=v; }
return a;
}, {}) )

// currently mixed is {"a":5,"b":2,"c":3,"d":{"e":4,"f":5,"g":null}}
// I want it to be {"a":5,"b":2,"c":3,"d":{"e":4,"f":5,g:1}}
alert(JSON.stringify(mixed))

最佳答案

带有一点下划线的 javascript 风格:

_.mixin({
extendNonNull: function(obj) {
_.each(_.rest(arguments,1), function(source) {
if (source) {
for (var prop in source) {
if( _.isObject(source[prop]) && _.isObject(obj[prop])){
obj[prop] = _.extendNonNull(obj[prop], source[prop]);
}
else if( !_.isNull(source[prop])){
obj[prop] = source[prop];
}
}
}
});
return obj;
}
});

var original = {a:1, b:2, c:3, d:{g:1}};
var fresh = {a:5, b:null,c:"", d:{e:4,f:5,g:null}};

var mixed = _.extendNonNull(original, fresh);

关于javascript - Underscore JS 使用新对象的非空值扩展对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21239242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com