In this article, I will explain object destructuring using pure Javascript and provide some examples of how I use it in my react project
How to use it with pure Javascript
- basic extract
The basic use of destructuring is to us {} to extract one or more properties from your object. The below example shows that you can extract and create a string variable with the same property name.
2. default value
If the destructed object don’t have the properties value, you can assign a default value, otherwise, it will return undefined. However, by assigning it with a value, it will not change your original object
3. Alias
If you want to extract property and give it a different name, you can use : to create an alias of it. Again, this will not change your original object.
4. Nested Object
Another popular way to use it is to extract a nested object, below example you can see that although currentRanking is in the nested layer, we can still extract is as a string
5. Rest Object
Combine it with rest syntax, you can extract multiple properties as an object variable.
Rest parameter and spread syntax: https://javascript.info/rest-parameters-spread
How I use it in my project
- Use in React Props
one of the common uses I find out is using it to pass in react props.
Let’s use this codeSandbox to explain the behavior: https://codesandbox.io/s/infallible-bogdan-6rt4h
In parent component ./WeatheraApp.js, with conditional rendering, I am passing some props down to ./WeatherCard.js and ./WeatherSetting.js.
Let's first check what happens in weather cards, when passing in props if you check it on console.log, you can see it’s passing in a props object with below properties
props: {
weatherElement:
moment:
fetchData:
setCurrentPage:
cityName:
}
Hence, in weatherCard we can extract these properties
In weatherSetting, we extract it when sending it over as a parameter, hence in weatherSetting function we can use cityName directly
Ref
- How to Use Object Destructuring in JavaScript: https://dmitripavlutin.com/javascript-object-destructuring/
- weatherApp project:https://ithelp.ithome.com.tw/articles/10222662