Abe
Abe

Reputation: 298

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?

Upvotes: 4

Views: 2167

Answers (2)

gongzhitaao
gongzhitaao

Reputation: 6682

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

Upvotes: 2

user1106925
user1106925

Reputation:

Just use i to view the key.

console.log(i);

Upvotes: 2

Related Questions