Instead of copying an object, we can clone it. To do that, we need to create a new object and iterate over the existing properties and copy them on the primitive level.
See the example below:
const person = {
name: "Doe",
age: 30
};
const clone = {};
// let's copy all person properties into it
for (let key in person) {
clone[key] = person[key];
}
console.log(clone); // { name: 'Doe', age: 30 }
console.log(person.name); // Doe
An alternative method is to use the Object.assign
syntax.
Object.assign(dest, [src1, ..., srcN])
Where,
dest
= target object
src1, ..., srcN
= source objects
All properties of src1, src2, src3...
are copied to dest
.
See the example below:
const person = { name: "Bello" };
const isDoctor = { check: false };
const favNum = { number: 69 };
console.log(person); // { name: 'Bello' }
const clonePerson = Object.assign(person, isDoctor, favNum);
console.log(clonePerson); // { name: 'Bello', check: false, number: 69 }
console.log(person); // { name: 'Bello', check: false, number: 69 }
console.log(clonePerson.name, clonePerson.check); // Bello false
console.log(person.name, person.check); // Bello false
person === clonePerson; // true
If the copied property name already exists, it gets overwritten:
const person = { name: "Bello" };
const myName= { name: "Doe" };
const favNum = { number: 69 };
console.log(person); // { name: 'Bello' }
Object.assign(person, myName);
console.log(person.name); // Doe
Object.assign
can also replace for...in
const person= {
name: "Bello",
favNum: 69
};
const clone = Object.assign({}, person);
console.log(clone); // { name: 'Bello', favNum: 69 }
Nesting Cloning
It is also possible for properties can be references to other objects
const person = {
name: "Bello",
details: {
age: 27,
isDoctor: false
}
};
person.details.age; // 27
Nested objects can be cloned.
See the example below:
const person = {
name: "Bello",
details: {
age: 28,
isDoctor: false
}
};
const clone = Object.assign({}, person);
person.details === clone.details; // true
Note: clone
and person
share the same details. This means clone.details
copies person.details
by reference.
person.details.age++; // 28 => change a property from one place
clone.details.age; // 29 => gets reflected at clone object
Instead, we should use deep cloning - a cloning loop that examines each value of user[key] and replicates values that are objects.
See more: Nested objects can be cloned - https://lodash.com/docs#cloneDeep
Happy coding!
TechStack Media | Domain
- Purchase a
.com
domain name as low as $9.99. - Purchase a
.net
domain name as low as $12.99. - Get cheaper domain names as low a $3.
- Build a website with ease.
Top comments (0)