简体   繁体   中英

iterating through JSON object with javascript

In this example, I would like to extract the 1) employee number and 2) all of her/his tasks. 2) works, but 1) gives me an object not the number...

Do I have to set employee number as key/value pair to be able to extract the value?

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);       
    }
}

I don't know why I am having trouble understanding this. Am I the only one?

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

console.log(i);
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]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM