var users = [
{ user: "Name1",geo:{lat:'12',long:'13'} },
{ user: "Name2",geo:{lat:'12',long:'13'}, age: 2 },
{ user: "Name2",geo:{lat:'12',long:'13'} },
{ user: "Name3",geo:{lat:'12',long:'13'}, age: 4 }
];
Above is the array of objects.
Here is the for-loop
I destructured and get user and age but I want lat and long also how will I do that ? I want it through destructuring and for-loop
like I did with user and age
for (let { user, age = "DEFAULT AGE" } of users) {
console.log(user, age);
}
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 to name
”.{}
means “check that the value to be destructured is an object or can be converted into one, i.e. is neither null
nor undefined
; create no variables”.{ prop }
means “get the value of prop
as the variable prop
”.{ prop: rename }
means “follow the prop
property and get its value as the variable rename
”1.{ prop = value }
means “get the value of prop
as the variable prop
, but assign value
if prop
yields undefined
”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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With