Reputation: 23
How to access property of object nested in array using destructuring? Following is my code:
var weatherObj = {
weather: [{
id: 721,
main: "Haze",
description: "haze",
icon: "50d"
}]
};
For example i want to decalre variable description with value "haze".
Upvotes: 2
Views: 178
Reputation: 14401
Decomposing all levels
You can decompose one level at a time. First, get the weather
property of weatherObj. Next, access the first element of the array in that property. Finally, you decompose the desired property from the element:
var {weather} = weatherObj
var [w1] = weather;
var {description} = w1;
Particular property with nesting
If you are only interested in the description
property, you can nest patterns as follows:
var {weather: [{description}]} = weatherObj;
// description === 'haze'
You can also assign the value to a variable with a different name than the property that you decompose just like you do it with the basic decomposition:
var {weather: [{description: desc}]} = weatherObj;
// desc === 'haze'
Upvotes: 2