我想做点像......
_.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))
答案 0 :(得分:2)
一点带有下划线的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);
答案 1 :(得分:0)
如果你使用lodash或下划线,你可以这样做:
import _ from 'lodash';
let result = _.merge({},target, source);
let clonedNonNull = _.omit(result,_.isNull);
答案 2 :(得分:0)
使用Lodash,您可以将过滤器功能作为 assignWith 功能的最后一个参数传递。
然后,您可以过滤 null 值或更具体的案例,并同时合并两个以上的对象。
let obj1 = {a: 'foo', b: null}
let obj2 = {a: null, b: 'bar'}
// acc is the accumulator value
function filter(acc, newValue) {
let isNull = _.isNull(newValue);
return isNull ? acc : newValue;
}
let mixin = _.assignWith({}, obj1, obj2, filter); // {a: 'foo', b: 'bar'}