JSON newb问:给出以下json数据:
{
"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" }
]
}
]
}
...并希望检索指定用户的日期&时间数据,以便可以呈现,例如:
Date 01: Time 01
Date 02: Time 02
Date 03: Time 03
我已经阅读了很多关于通过数组和对象进行循环的内容,但我仍然对如何获取日期和对象感到困惑。时间(或任何键/值),如果键是唯一的。到目前为止,我有这个:
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
}
顺便说一句:学习javascript,而不是使用jquery等。
非常感谢,
SVS
答案 0 :(得分:1)
由于datesAndTimesArray
是一个对象数组,因此需要一个嵌套循环来处理它。
for (var i in datesAndTimesArray) {
var obj = datesAndTimesArray[i];
for (var date in obj) {
console.log('Date ' + date + ': Time' + obj[date]);
}
}
日期和时间可能更好的是单个对象而不是数组,例如
"dates & times": {
"2014.08.01": "120.0",
"2014.08.02": "123.0",
"2014.08.03": "126.0"
}
然后你只需要做for (date in datesAndTimesArray)