In the previous article, we've seen how to extract property values from an object and store them as variables.
const person = {
name: 'Bello',
age: 27,
size: {
height: 6.7,
weight: 220
}
};
const heightSize = person.size.height;
// const weightSize = person.size.weight;
console.log(`${person.name} is ${heightSize}" tall.`);
There's a technique called destructured assignment that easily extracts properties from an object.
Syntax:
{ key } = obj;
See the example below:
const person = {
name: 'Bello',
age: 27,
size: {
height: 6.7,
weight: 220
}
};
const { name } = person;
const { age } = person;
console.log(`${name} is ${age} years old.`);
Multiple property names in the same object (above example) can be accessed as shown below:
const { name, age } = person;
console.log(`${name} is ${age} years old.`);
To extract a nested object property, the syntax is shown below:
Syntax:
{ keyN } = globalObj.objkey1.objkey2...objkeyN;
See the example below:
const person = {
name: 'Bello',
age: 27,
size: {
height: 6.7,
weight: 220
}
};
const { name } = person;
// const { height } = person.size;
const { weight } = person.size;
console.log(`${name} weighs ${weight}lbs.`);
See more examples below:
let a, b, c = 4, d = 8; // a = 4, b = 4, c = 4, d = 8
[ a, b = 6 ] = [ 2 ]; // a = 2, b = 6
[ c, d ] = [ d, c ] // [ 8, 4 ] => c = 8, d = 4
let x, y;
( { x, y } = { x: 'Hello ', y: 'Bello' } );
console.log(x + y); // Hello Bello
let person = { name: 'Bello', isTrue: true }
let { name: lastName, isTrue: t } = person;
console.log(lastName); // Bello
/* console.log(name); // ReferenceError: name is not defined */
let user = { lName: 'Bello', id: '3kwe9i' };
let { lName = 'Doe', isTrue = false } = user;
console.log(lName); // Bello
console.log(isTrue); // false
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)