JSON newb asking: Given the following json data:
{
"Users": [
{
"userName": "Herbie",
"dates & times": [
{ "2014.08.01": "120.0" },
{ "2014.08.02": "123.0" },
{ "2014.08.03": "126.0" }
]
},
{
"userName": "Wayne",
"dates & times": [
{ "2014.08.01": "120.0" },
{ "2014.08.02": "123.0" },
{ "2014.08.03": "126.0" }
]
},
{
"userName": "Freddie",
"dates & times": [
{ "2014.08.01": "120.0" },
{ "2014.08.02": "123.0" },
{ "2014.08.03": "126.0" }
]
},
{
"userName": "Ron",
"dates & times": [
{ "2014.08.01": "120.0" },
{ "2014.08.02": "123.0" },
{ "2014.08.03": "126.0" }
]
},
{
"userName": "Tony",
"dates & times": [
{ "2014.08.01": "120.0" },
{ "2014.08.02": "123.0" },
{ "2014.08.03": "126.0" }
]
}
]
}
... and wanting to retrieve a specified user's dates & times data so it can be rendered, e.g.:
Date 01: Time 01
Date 02: Time 02
Date 03: Time 03
I've read much about looping thru arrays and objects but I'm still confused as to how to get the dates & times (or any keys/values) if the keys are unique. So far I have this:
var usersArray = myObj["Users"];
for (var user in usersArray){
if (!usersArray[user].userName == selUser) {
alert("user not found");
}
else if (usersArray[user].userName == selUser) {
var datesAndTimesArray = usersArray[user]["dates & times"];
console.log(selUser +"'s dates & times: " + datesAndTimesArray); // returns array of objects
}
}
for (var someKey in datesAndTimesArray){
// here's where I'm struggling, trying to get all the dates & times for the selected user, such that I can render it as described above
// pseudo-code
}
Btw: studying javascript, not using jquery etc.
Many thanks in advance,
svs
alert. If you're looking forFreddie, you'll alert "user not found" when the loop looks at Herbie and Wayne before him. And usebreakwhen you find the user you want.forloop to loop arrays, not afor..in.for ... inloops for iterating through arrays in JavaScript. Use a plainforloop and an index variable to explicitly count through the properties, or else use the.forEach()method.date & timeshould be a single object, not an array of objects with one property each. Thenfor (var someKey in datesAndTimesArray){would work just fine.