I have objects (people) inside an array (group) inside an object (data) like so:
const data = {
g1 : [
{"name" : "Jack", "age" : 32},
{"name" : "Jill", "age" : 44}
],
g2 : [
{"email" : "jane@example.com", "city" : "Berlin", "age" : 14},
{"email" : "brad@example.com", "city" : "Stockholm", "age" : 22}
]
}
Say I want to console.log
all age property values, I try:
for (const group in data) {
for (const person of group) {
console.log(person.age)
}
}
This does not work. It seems for (const group in data)
is only looping over the names of it's children. I assume I should not use for...in
in this case, but what can I use? Or is it somehow possible to use for...in
?
The reason I'm confused is because in for example PHP I could do:
<?php
$data = [
"g1" => [
[ "name" => "Jack", "age" => 32 ],
[ "name" => "Jill", "age" => 44 ]
],
"g2" => [
[ "email" => "jane@example.com", "city" => "Berlin", "age" => 14 ],
[ "email" => "brad@example.com", "city" => "Stockholm", "age" => 22 ]
]
];
foreach ( $data as $group ) {
foreach ( $group as $person ) {
echo $person[ 'age' ];
}
}
and in would work.