Wrecking my head today trying to find out how to loop through and log out the name of each object.
Here is the JSON response:
{
"placeListings": {
"OBJ1": {
"Active": true,
"Name": "place 1"
},
"OBJ2": {
"Active": true,
"Name": "place 2"
},
"OBJ3": {
"Active": true,
"Name": "place 3"
}
}
}
I would like to parse out the "Name" part in a for loop
for (let i = 0; i < res.length; i ) {
console.log("NAME: " res.placeListings.OBJ1.Name);
}
But I don't know how to iterate through OBJ1/OBJ2/OBJ3 etc..
Any help is welcome!
CodePudding user response:
The placeListings
is an object, not an array.
So you need to use the Object.keys
method to get the object's keys
const source = {
placeListings: {
OBJ1: {
Active: true,
Name: 'place 1'
},
OBJ2: {
Active: true,
Name: 'place 2'
},
OBJ3: {
Active: true,
Name: 'place 3'
}
}
}
const keys = Object.keys(source.placeListings)
console.log(keys)
for (let i = 0; i < keys.length; i ) {
console.log(source.placeListings[keys[i]])
}
CodePudding user response:
You can simply achieve this with a single line of code by using Object.keys() and Array.forEach() method.
Demo :
const res = {
"placeListings": {
"OBJ1": {
"Active": true,
"Name": "place 1"
},
"OBJ2": {
"Active": true,
"Name": "place 2"
},
"OBJ3": {
"Active": true,
"Name": "place 3"
}
}
};
Object.keys(res.placeListings).forEach(key => console.log(res.placeListings[key].Name));