Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inner like merge in lodash

I am trying to do an object merge with lodash in node.js. The merge works great in the fact that it won't overwrite property objects that result in undefined.

However I would like the means for it to only overwrite objects that exist in the destination object. See example below:

var e1 = {
    name: 'Jack',
    surname: 'Root'
};

merge with

var e2 = {
    name: 'Rex',
    surname: undefined,
    age: 24
};

Current result:

{
    name: 'Rex',
    surname: 'Root',
    age: 24
}

result I would like:

{
name: 'Rex',
surname: 'Root'
}

So what I am trying to get is for the source object to only overwrite properties that exist in both, and only if they are not undefined.

I tried searching for other functions, but only found merge and assign to do similar things. But alas it is not exactly what I wanted.

The whole idea behind this is to build some method that will get objects fields from a web form and then bind them to a mongoose.js model object for persisting.

This is to avoid always having to manually bind each property to another object.

like image 744
Whesley Barnard Avatar asked Apr 22 '15 13:04

Whesley Barnard


2 Answers

I couldn't figure out a very convenient way to do this with lodash methods, but it's not too difficult to do using vanilla:

// Only loop over e1 values
for (var e1k in e1) {
    // Use e2 value if it exists, otherwise stick with what is already there
    e1[e1k] = e2[e1k] || e1[e1k];
}
like image 79
Explosion Pills Avatar answered Oct 20 '22 20:10

Explosion Pills


You could use _.mapValues:

var e1 = {
    name: 'Jack',
    surname: 'Root'
};
var e2 = {
    name: 'Rex',
    surname: undefined,
    age: 24
};

var result = _.mapValues(e1, function (n, e) {
    return e2[e] || n;
});
console.log(result);
like image 31
xdazz Avatar answered Oct 20 '22 19:10

xdazz