To clone or copy a JavaScript object, you can use Destructuring Assignment.
The
destructuring assignment
syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.In this tutorial, I will show you how to clone a JavaScript object using Destructuring Assignment.
Cloning Javascript object
To clone a Javascript object, you can use the array destructuring syntax { ...object }
on your object.
const person = {
id:"704a9b5e-e7dc-445f-994d-d61df95db949",
name:"Wilson",
age: 45,
gender:"male"
}
const personClone = {...person};
console.log(personClone);
// 👇🏼 See the output below
{
id: '704a9b5e-e7dc-445f-994d-d61df95db949',
name: 'Wilson',
age: 45,
gender: 'male'
}
Cloning Javascript object except one property
For omitting one property from your object clone, you can list it before the destructuring like this – { ignoredProperty, ...otherProperties }
, so that it will be ignored.
const person = {
id:"704a9b5e-e7dc-445f-994d-d61df95db949",
name:"Wilson",
age: 45,
gender:"male"
}
const {age,...otherProperties} = person;
const personClone = {...otherProperties};
console.log(personClone);
// 👇🏼 See the output below
{
id: '704a9b5e-e7dc-445f-994d-d61df95db949',
name: 'Wilson',
gender: 'male'
}
Cloning Javascript object except some property
For omitting many properties from your object clone, you can list it before the destructuring like this { ignoredProperty1, ignoredProperty2 ,...otherProperties }
so that it will be ignored.
const person = {
id:"704a9b5e-e7dc-445f-994d-d61df95db949",
name:"Wilson",
age: 45,
gender:"male"
}
const {age, gender ,...otherProperties} = person;
const personClone = {...otherProperties};
console.log(personClone);
// 👇🏼 See the output below
{
id: '704a9b5e-e7dc-445f-994d-d61df95db949',
name: 'Wilson'
}
Author : Kevin Kouomeu
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments section 💬.
My goal with this blog is mainly to create helpful content for
Connect with me here LinkedIn • Twitter • Instagram • GitHub or Medium
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments section 💬.
My goal with this blog is mainly to create helpful content for
Java
and Javascript
web devs, if you want to discuss a specific topic related to the programming world, you can reach me on my social platforms. Connect with me here LinkedIn • Twitter • Instagram • GitHub or Medium