المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: syahshiimi’s notes, The Complete JavaScript Course 2022 From Zero to Expert
We can also destructure the properties in the object like we can do in Array Destructuring.
Simple Object Destructuring
We can destructure with the use of {}
in a const
variable, similar to how we use it to create an object.
We then reference to the object itself with the -“js const { name, openingHours, categories } = restaurant; // restaurant is an object console.log(name, openingHours, categories); // return values of the properties name, openingHours and categories
## Referencing Same Properties but Use Different Name
- We can use this example to rename the properties in the object.
- This is very useful when we are working with third-party APIs and requiring to extract values with unknown variable names.
```js
// property: variableName
const { name: restaurantName, openingHours: hours, categories: tags } = restaurant;
console.log(restaurantName, hours, tags);
Dealing With Non-explicitly Defined Data Using Default Values
- Often when dealing with non-explicit defined data, we may find this method useful to give default values to create empty properties.
- This would be useful because we would have zero clue on the amount of data that we are receiving.
This is useful for creating your own array from an API response etc.
How Can We Mutate Variables In an Object?
Where the variables in the object needs to be redefined, we can mutate it within the object itself by destructuring its contents.
We can use the simple method of destructuring an array, as seen in Array Destructuring.
Obtaining Variables In a Nested Object
While we can use a simple const { property } = objectName
to get the objects, we can also instead use a nested function within the declaration above to get the value of the variable itself.
Dealing With Methods (functions In Objects) With Multiple Args
- It can be difficult to track the order of which the arguments of a function should be written.
- This method of having objects into function arguments is very common in many JavaScript libraries.
- It is useful because the main object method does the destructuring for you instead.
- This way the order of argument is optional, it doesn’t need to be the same.