Clone object in JavaScript

Home /

Table of Contents

About JavaScript Object

In JavaScript, an object is a collection of properties. Each property has a name and a value. The value can be a primitive data type (such as a string or number), or it can be a reference to another object.

Objects are created using the object literal notation {} or using the object constructor (‘new Object()’). Properties can be added to an object using dot notation (‘object.property = value’) or square bracket notation (‘object[‘property’] = value’).

Objects can also have methods, which are functions that are associated with an object and can be called using the dot notation.

For example:

JavaScript
const person = {
    name: "John Doe",
    age: 30,
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

person.greet(); // outputs "Hello, my name is John Doe"

In JavaScript, objects are used to represent many things including but not limited to, arrays, functions, classes and the document object model (DOM).

JavaScript objects are also passed by reference, meaning that when an object is assigned to a variable or passed as an argument, the variable or argument is given a reference to the object, not a copy of the object.

Clone JavaScript Object

There are several ways to clone a JavaScript object, but some methods are more efficient than others.

One efficient way to clone an object is to use the spread operator (…), which creates a new object with the same properties as the original. For example:

JavaScript
const original = {a: 1, b: 2};
const clone = {...original};

Another efficient way to clone an object is to use the ‘Object.assign()’ method, which creates a new object and copies the properties of one or more source objects to it. For example:

JavaScript
const original = {a: 1, b: 2};
const clone = Object.assign({}, original);

Additionally, JSON.parse(JSON.stringify(obj)) can also be used to clone an object, it will be a deep clone but it will remove any methods and prototype properties.

It’s important to note that these methods create a shallow copy of the object, meaning that if the object contains any nested objects or arrays, those will be copied by reference and not by value.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit
Other Recommended Article