Marcelo Lazaroni Marcelo Lazaroni - 1 month ago 5
Javascript Question

How to create a new object with overshadowed properties in lodash?

I want to create a new object (not modifying any existing one) with the properties of object A and the property values of object B, if the property exists in object B, if it doesn't then default to the values in object A.

It's similar to

Object.assign({}, a, b)
but ignoring all keys that are not in the second parameter.

Is there any way to do that with Lodash?

Here is a native JS implementation of what I'm looking for:



function overshadow(oldObj, newObj) {
return Object.keys(oldObj)
.reduce((result, key) => {
result[key] = newObj[key] || oldObj[key];
return result;
}, {});
};

a = { one: 1, two: 2 };

b = { one: 'a', three: 'b' };

c = overshadow(a, b);

console.log(c) // { one: "a", two: 2 }




Answer

You can use _.pick() with Object.keys() or _.keys() to take from the newObj only the properties that exist in the oldObj:

a = { one: 1, two: 2 };
b = { one: 'a', three: 'b' };

function overshadow(oldObj, newObj) {
  return _.assign({}, oldObj, _.pick(newObj, Object.keys(oldObj)));
}

var result = overshadow(a, b);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Comments