JavaScript(JS) JS clone a js object
In JavaScript, you can clone an object using several methods. Here are two common approaches:
- Using the
Object.assign()
method:
const myObj = { name: 'John', age: 30 }; const clonedObj = Object.assign({}, myObj);
In the above example, we declare an object myObj
and assign it some key-value pairs. We then use the Object.assign()
method to clone the object. We pass an empty object {}
as the first argument, which will be the target object for the assignment. We then pass the object we want to clone myObj
as the second argument.
The Object.assign()
method creates a new object and copies all enumerable own properties from the source objects to the target object. In this case, it copies all key-value pairs from myObj
to the empty object, creating a clone of myObj
.
- Using the spread operator
...
:
const myObj = { name: 'John', age: 30 }; const clonedObj = { ...myObj };
In the above example, we use the spread operator ...
to create a new object clonedObj
with all the properties of myObj
. The spread operator creates a shallow copy of the object, meaning that it only copies the object's own enumerable properties.
Note that if the object being cloned has nested objects or arrays as its properties, the nested objects and arrays will still be referencing the original object's properties. In such cases, you would need to perform a deep clone of the object to ensure that all properties are cloned recursively.