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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

Node.js puppeteer - Use values from array in a loop to cycle through pages