How to destructure nested objects in for-loop
You can use this:
for (let {user, age = "DEFAULT AGE", geo: {lat, long}} of users) {
console.log(user, age, lat, long);
}
You have already successfully destructured user
(simply by the property name in the object) and age
(with a default value as well).
To use nested destructuring, step by step, simply put the property name geo
in there as well, since that’s the next property on the objects you’re iterating over that contains your needed values:
{user, age = "DEFAULT AGE", geo}
— this would yield {lat: "12", long: "13"}
for geo
.
To access the nested properties directly, follow the object structure:
{user, age = "DEFAULT AGE", geo: {}}
— this would just validate that geo
is indeed an object.
Then, list the properties you want to access in that object:
{user, age = "DEFAULT AGE", geo: {lat, long}}
— this would yield "12"
for lat
and "13"
for long
.
You could even go a step further and rename those properties:
{user, age = "DEFAULT AGE", geo: {lat: latitude, long: longitude}}
— this would yield "12"
for latitude
and "13"
for longitude
.
These are the basic cases for destructuring objects:
name
means “just assign the entire value toname
”.{}
means “check that the value to be destructured is an object or can be converted into one, i.e. is neithernull
norundefined
; create no variables”.{ prop }
means “get the value ofprop
as the variableprop
”.{ prop: rename }
means “follow theprop
property and get its value as the variablerename
”1.{ prop = value }
means “get the value ofprop
as the variableprop
, but assignvalue
ifprop
yieldsundefined
”2.
For the “rename” case, the rules apply recursively: rename
is like name
, so it can be replaced by {}
, or { anotherProp }
, or { anotherProp: anotherRename }
, or { anotherProp = anotherDefault }
, etc.
Other properties on the same object level may be added via commas, like {propA, propB}
.
For arrays, similar cases exist: []
would validate that the value to be destructured is an iterable object; [a, b]
has the same meaning as {0: a, 1: b}
; etc.
1: Note that in the case of { prop: something }
no variable prop
is created.
2: “yields undefined
” means that obj.prop
would be equal to undefined
which means either that the property exists and has the literal value undefined
or that the property doesn’t exist.
If you're just trying to find a given user and return the geo for it, this will do:
users.find( u => u.user === 'Name1' ).geo;
Keep in mind, you would want to do some checks aginst your 'find result' before trying to use it. For example:
const user = users.find( u => u.user === 'Name1' );
if (user && user.hasOwnProperty('geo')) {
console.log(user.geo);
}