how to use the assign function from the underscore library in javascript

The _.assign() function from the Underscore library in JavaScript is used to copy the values ​​of all enumerable properties from one or more source objects to a target object. This function mutates the target object.

Here is an example:

index.tsx
const _ = require('underscore');

const targetObj = { a: 1 };
const sourceObj1 = { b: 2 };
const sourceObj2 = { c: 3 };

_.assign(targetObj, sourceObj1, sourceObj2);

console.log(targetObj);
// Output: { a: 1, b: 2, c: 3 }
223 chars
11 lines

In this example, we first import the Underscore library using require(). We then create a targetObj and two sourceObjs. By passing all three objects as arguments to _.assign(), we copy the key-value pairs from sourceObj1 and sourceObj2 over to targetObj. The console.log() statement outputs the final targetObj to confirm that _.assign() has successfully copied all properties into it.

gistlibby LogSnag