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?

Answers


Just use i to view the key.

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

Need Your Help

Redirect domain name mapped with external IP (modem) to a host in its local network

networking dns routing router

I have a modem that is connected to a router. There are two computers connected to this router. I want to set a domain for one of those computers so that I can access the web deployment server runn...

Html as string on MVC5 Razor

asp.net-mvc razor

Currently, I store Html in database and populate into a Dropdownlist like this I'm using @funcion in Razor:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.