Saturday, 18 January 2025

Mastering JavaScript's Spread Operator: Copying and Updating Object

The JavaScript spread operator (...) has become a powerful and widely-used feature in modern JavaScript development. It simplifies common tasks like copying and merging objects and arrays, making code more readable and short.

What is the Spread Operator?

The spread operator, represented by three dots (...), was introduced in ES6 (ECMAScript 2015). It allows you to unpack the values of an object or array into another object or array. In simple terms, it "spreads" the properties or elements into a new structure.

 

When used with objects, the spread operator allows you to copy existing properties into a new object, update specific properties, or merge multiple objects together. In summary, it creates shallow copies, which is a key concept to understand when dealing with nested structures.

const user = { name: "Krishna", age: 34, city: "Bangalore" };

// Update name
const userNameUpdated = { ...user, name: "Gopi" };

 

...user creates a shallow copy of the user object, meaning all properties from user are copied into a new object. After copying all properties, the name property is overwritten with "Gopi".

// Update city
const cityUpdated = { ...user, city: "Chennai" };

 

...user again creates a shallow copy of the original user object. The city property is updated to "Chennai", while the rest of the properties stay the same.

// Update name and age
const nameAndAgeUpdated = { ...user, name: "Rahul", age: 37 };

 

As in previous examples, ...user copies the original user object into the new object. This time, both name and age are updated at the same time. The new name is "Rahul" and the new age is 37.

 

spread_operator_demo.js

const user = { name: "Krishna", age: 34, city: "Bangalore" };

// Update name
const userNameUpdated = {...user, name: "Gopi"}

// Update city
const cityUpdated = {...user, city: "Chennai"}

// Update name and age
const nameAndAgeUpdated = {...user, name: "Rahul", age: 37}

console.log('user: ' + JSON.stringify(user));
console.log('userNameUpdated: ' + JSON.stringify(userNameUpdated));
console.log('cityUpdated: ' + JSON.stringify(cityUpdated));
console.log('nameAndAgeUpdated: ' + JSON.stringify(nameAndAgeUpdated));

 

Output

user: {"name":"Krishna","age":34,"city":"Bangalore"}
userNameUpdated: {"name":"Gopy","age":34,"city":"Bangalore"}
cityUpdated: {"name":"Krishna","age":34,"city":"Chennai"}
nameAndAgeUpdated: {"name":"Rahul","age":37,"city":"Bangalore"}

 

Merging objects

You can merge two or more objects into a single object using the spread operator.

 

merge_objects.js

 

const emp = {name : "Krishna", "age" : 36};
const address = {state: "Karnataka", country : "India"};

const empWithAddress = {...emp, ...address};

console.log(`emp : ${JSON.stringify(emp)}`);
console.log(`address : ${JSON.stringify(address)}`);
console.log(`empWithAddress : ${JSON.stringify(empWithAddress)}`);

Output

emp : {"name":"Krishna","age":36}
address : {"state":"Karnataka","country":"India"}
empWithAddress : {"name":"Krishna","age":36,"state":"Karnataka","country":"India"}

In this example, the spread operator (...) is used to combine two separate objects, emp and address, into a new object called empWithAddress. Let’s break it down step-by-step.

 

Working with Nested Objects

For nested objects, you can use the spread operator at multiple levels to update specific properties.

 

nested_objects.js

const emp = {
  name: "krishna",
  age: 36,
  address: { state: "Karmataka", city: "Bangaalore" },
};

const empUpdatedWithCity = {
    ...emp,
    address: {...emp.address, city: "Chennai"}
}

console.log(`emp : ${JSON.stringify(emp)}`);
console.log(`empUpdatedWithCity : ${JSON.stringify(empUpdatedWithCity)}`);

Output

emp : {"name":"krishna","age":36,"address":{"state":"Karmataka","city":"Bangaalore"}}
empUpdatedWithCity : {"name":"krishna","age":36,"address":{"state":"Karmataka","city":"Chennai"}}

Above snippet creates a new empUpdatedWithCity object by copying all properties from emp using the spread operator. It updates only the city inside the nested address object to "Chennai", while keeping the other properties (like state and the top-level properties) unchanged. The original emp object remains unmodified


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment