Categories
JavaScript Answers

How to call Lodash assign only if property exists in target object with JavaScript?

Spread the love

Sometimes, we want to call Lodash assign only if property exists in target object with JavaScript.

In this article, we’ll look at how to call Lodash assign only if property exists in target object with JavaScript.

How to call Lodash assign only if property exists in target object with JavaScript?

To call Lodash assign only if property exists in target object with JavaScript, we can use the pick and keys method to return an object that only has the keys in the target object.

For instance, we write:

const options = {
  foo: 1,
  bar: 2
}
const defaults = {
  foo: 2,
  baz: 3
}
const o = _.assign(options, _.pick(defaults, _.keys(options)));
console.log(o)

to call pick with the defaults object and the properties that are only in options to return an object with the properties that are only in options.

Then we call assign with options and the returned object to return a new object with the options properties overridden by the properties in the object returned by pick.

Therefore, o is

{
  bar: 2,
  foo: 2
}

Conclusion

To call Lodash assign only if property exists in target object with JavaScript, we can use the pick and keys method to return an object that only has the keys in the target object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *