how to use the assign function from lodash in javascript

_.assign(object, [sources]) is a method from lodash that copies the values of all enumerable properties from one or more source objects to a target object, and returns the target object.

Here's an example:

index.tsx
const lodash = require('lodash');

const targetObject = {
  a: 1,
  b: 2
};

const sourceObject = {
  b: 4,
  c: 5
};

const resultObject = lodash.assign(targetObject, sourceObject);

console.log(resultObject); // { a: 1, b: 4, c: 5 }
235 chars
16 lines

In the example above, we first require the lodash library. Then we create a targetObject with two properties a and b, and a sourceObject with two properties b and c.

We then call lodash.assign and pass it our targetObject as the first parameter, and our sourceObject as the second parameter. The function merges both objects and returns the result.

The final console.log statement outputs the result:

index.tsx
{ a: 1, b: 4, c: 5 }
21 chars
2 lines

Note how the value of the property b in the targetObject has been overwritten by the value of the property b in the sourceObject. The other properties are preserved, and the new property c is added to the targetObject.

gistlibby LogSnag