/**
* @class : file
* @author : Shekhar Suman ([email protected])
* @created : Thursday Dec 22, 2022 20:02:47 IST
* @description : file
*/
employee = '[{"firstName": "John", "lastName": "Stoke", "Salary": 5000, "permanentStaff": true}]';
const object = JSON.parse(employee);
//console.log(object[0])
for(var ele in object[0]){
console.log(`${ele}`);
}
How to print values for instance John, Stoke, 5000, true in same for loop?
I tried using object[0].ele and object[0].${ele}
to get John, Stoke, 5000, true but failed to do so.
2
Answers
You’re printing the property name here:
Instead, use that name to access the property itself:
Exactly what David says here.
You’re accessing the first layer of a two dimensional array with the foreach() loop.
Say you ordered multiple packages online and they got delivered in one large box. Because they’re different products they’re all individually packed within the large box they got delivered in.
With the foreach() loop you basically open the large box, meaning you still have the individual packages left to open. Using a new index on the opened large box you then point at the next box you want to open.
Hope that makes sense as far as the theory goes, for the direct answer you’re best off taking David’s here.