How to Create a Shallow Clone of a Value using Lodash ?
Shallow copy is the process of duplicating an object or array at the top level without copying nested objects or arrays.
Below are the possible approaches to creating a shallow clone of a value using Lodash.
Table of Content
- Using clone() function
- Using assign() function
Run the below command before running the code in your local system:
npm i lodash
Using clone() function
In this approach, we are using the clone() function of Lodash to create a shallow copy of the originalObj, making sure that changes made to res do not affect originalObj.
Syntax:
_.clone(value);
Example: The below example uses the clone() function to create a shallow clone of a value using Lodash.
const _ = require('lodash');
let originalObj = {
name: 'GFG',
age: 30
};
let res = _.clone(originalObj);
console.log(res);
Output:
{ name: 'GFG', age: 30 }
Using assign() function
In this approach, we are using the assign function of Lodash to create a shallow copy of originalObj by assigning its properties to an empty object, making sure that res is an independent copy.
Syntax:
_.assign( dest_object, src_obj );
Example: The below example uses assign() function to create a shallow clone of a value using Lodash.
const _ = require('lodash');
let originalObj = {
name: 'GFG',
age: 25 };
let res = _.assign({}, originalObj);
console.log(res);
Output:
{ name: 'GFG', age: 25}
Contact Us