Get key value from an object while looping
Get key value from an object while looping
I am lost on getting the value of height from this object for each person:
[object Object]
Adam: [object Object]
height: 192,
weight: 101
,
Grant: [object Object]
height: 171,
weight: 79
I just keep getting undefined or printing out the name.
const personData = data
Object.keys(personData).forEach((person, index) =>
console.log(person)
)
The above will just console log the name, person[0] gives me the first letter of each name and my other attempts produce undefined.
person[0]
How do I navigate to the correct value and key?
2 Answers
2
This is happening because you're iterating over the root of the object. The height, weight etc details live in sub-objects at a deeper level.
You're going to need to iterate over the object's values, not its keys, then reach in a little deeper to extrac the height property:
height
Object.values(personData).forEach((person, index) =>
console.log('Height = '+person.height);
//if you need to access the person name too...
console.log('Person = '+Object.keys(personData)[index]);
)
You are iterating over the keys of the object. In this case "Adam" and "Grant". What you want to do is to use these keys to access the object - and that is your person:
const personData = data
Object.keys(personData).forEach((name, index) =>
console.log(personData[name])
)
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.