Eu gostaria de fazer algo como ...
_.extend(original, fresh);
Mas apenas para copiar atributos que não são nulos, então ...
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}
Atualizações
Fiz alguns progressos, mas não funciona com objetos aninhados ...
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))
Respostas:
2 para resposta № 1Um toque de javascript com um traço de sublinhado:
_.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);
0 para resposta № 2
se você estiver usando lodash ou sublinhado, é assim que você pode fazer:
import _ from "lodash";
let result = _.merge({},target, source);
let clonedNonNull = _.omit(result,_.isNull);
0 para resposta № 3
Usando Lodash você pode passar uma função de filtro como último parâmetro do assignWith função.
Então você pode filtrar o nulo valores ou casos mais específicos e mesclar mais de 2 objetos ao mesmo tempo.
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"}