DEV Community

Cover image for JavaScript Object Clone
Bello Osagie
Bello Osagie

Posted on • Edited on

4

JavaScript Object Clone


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
Enter fullscreen mode Exit fullscreen mode

An alternative method is to use the Object.assign syntax.

Object.assign(dest, [src1, ..., srcN])
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode


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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!


Buy me a Coffee


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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay