4

在这个例子中,我想提取 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);       
    }
}

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

4

2 回答 2

2

只需用于i查看密钥。

console.log(i);
于 2013-05-03T02:02:36.553 回答
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]);
    }
}
于 2013-05-03T02:06:25.847 回答