使用javascript迭代JSON对象

时间:2013-05-03 02:00:33

标签: javascript json

在这个例子中,我想提取1)员工编号和2)她/她的全部 任务。 2)工作,但1)给我一个对象而不是数字...

我是否必须将员工编号设置为键/值对才能提取值?

var s = {
    "schedule": {
        "employees": {
            "1000": {
                "tasks": [
                    {
                        "task": "task1",
                        "site": "site1",
                        "from": "0900",
                        "to": "1000"
                    },
                    {
                        "task": "task2",
                        "site": "site2",
                        "from": "0900",
                        "to": "1000"
                    }
                ]
            },
            "2000": {
                "tasks": [
                    {
                        "task": "task3",
                        "site": "site3",
                        "from": "0900",
                        "to": "1000"
                    },
                    {
                        "task": "task4",
                        "site": "site4",
                        "from": "0900",
                        "to": "1000"
                    }
                ]
            }
        }
    }
}

for (var i in s["schedule"]["employees"]) {
    // this gives me the object, I would like the employee number (eg:1000)
    console.log(s["schedule"]["employees"][i]);

    // this gives me the task number 
    for (var j in s["schedule"]["employees"][i].tasks) {
        console.log(s["schedule"]["employees"][i].tasks[j].task);       
    }
}

我不知道为什么我无法理解这一点。我是唯一一个吗?

2 个答案:

答案 0 :(得分:2)

只需使用i即可查看密钥。

console.log(i);

答案 1 :(得分:2)

for (u in s.schedule.employees) {
    console.log(u);
    for (v in s.schedule.employees[u]) {
        for (var i =0; i < s.schedule.employees[u]['tasks'].length; ++i)
            for (var j in s.schedule.employees[u]['tasks'][i])
                console.log(j);
                console.log(s.schedule.employees[u]['tasks'][i][j]);
    }
}