Home >Web Front-end >JS Tutorial >JavaScript Object Destructuring
Destructuring Objects
Like destructuring arrays, destructuring objects helps you and makes your code cleaner and better, but it’s different from destructuring arrays, here is how to do it:
let heightInCm = 4; const obj = { personName: 'spongeBob', personAge: 37, personAddress: '124 Conch Street, Bikini Bottom, Pacific Ocean', heightInCm: 10, personHobbies: [ 'Jellyfishing', 'Cooking Krabby Patties', 'Blowing Bubbles', 'Karate', ], home: { type: 'pineapple', location: 'bikini bottom', details: { rooms: 3, uniqueFeature: "it's underwater and shaped like a pineapple!", }, }, };
const { personName, personAge } = obj; console.log(personName, personAge); // spongeBob 37
*You can also make variable names different from the property names, just right the new variable name after a colon:
const { personName: name, personAge: age } = obj; console.log(name, age); // spongeBob 37
*Default Values:
const { DriversLicense = ['no'] } = obj; console.log(DriversLicense); // ['no'] // DriversLicense does not exist in obj, so the default value will be used.
* Mutating Variables while Destructuring Objects:
({ heightInCm } = obj); console.log(heightInCm); // 10
*Nested object destructuring:
// firstway: Extracting the Entire Nested Object const { details } = obj.home; console.log(details); // { rooms: 3, uniqueFeature: "it's underwater and shaped like a pineapple" // second way: Extracting Specific Properties const { home: { details }} = obj; console.log(details); // {rooms: 3, uniqueFeature: "it's underwater and shaped like a pineapple" // third way const {details: { rooms, uniqueFeature }} = obj.home; console.log(rooms, uniqueFeature); // 3 "it's underwater and shaped like a pineapple!"
*Thanks for reading, hope you understand everything, if you have any questions feel free to ask ?
The above is the detailed content of JavaScript Object Destructuring. For more information, please follow other related articles on the PHP Chinese website!