Object rest and spread

When working with basic JavaScript objects, we often need to copy the properties of one object to another, or do some mixing and matching of properties from various objects. Similar to the way that we defined a function as having a variable number of arguments, we can use this same syntax on standard objects. This technique is called object rest and spread. Consider the following TypeScript code:

let firstObj = { id: 1, name: "firstObj" }; 
 
let secondObj = { ...firstObj }; 
console.log(`secondObj : ${JSON.stringify(secondObj)}`); 

Here, we start by defining a simple JavaScript object named firstObj, that has an id and a name property. We then use the new ES7 syntax to copy all of the properties of firstObj into another object called secondObj, by using the rest syntax, which is three dots preceding the variable { ...firstObj }. To test that this has indeed copied all properties, we then log the value of the secondObj variable to the console. The output of this code is as follows:

secondObj : {"id":1,"name":"firstObj"}

Here, we can see that the values of the id and name properties have been copied from firstObj into secondObj, using the rest ES7 syntax.

We can also use this syntax to combine multiple objects together. This is known as object spread, as follows:

let nameObj = { name: "nameObj" }; 
let idObj = { id: 2 }; 
 
let obj3 = { ...nameObj, ...idObj }; 
console.log(`obj3 : ${JSON.stringify(obj3)}`); 

Here, we have an object named nameObj, which defines a single property named name. We then define a second object named idObj that defines a single property named id. We then create obj3, out of nameObj and idObj, by using the rest syntax { ...nameObj, ...idObj }. This syntax means that we intend to copy all properties from nameObj, and all properties from idObj into a new object named obj3. The result of this code is as follows:

obj3 : {"name":"nameObj","id":2}

This shows us that both objects' properties have been merged into a single object, using object spread.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.151.141