How to access array within associative array in jquery

Viewed 42

I am retrieving JSON data from a remote server in an associative array format . The structure of the associative array is:

data=
{
"1":[{"project_id":1,"project":"IET1"},{"project_id":2,"project":"IET2"}],
"2":[{"project_id":3,"project":"IET3"}],
"3":[{"project_id":4,"project":"IET4"},{"project_id":5,"project":"IET5"}]
}

This is the exact format that I am getting from the ajax response. Now when I trying to traverse it using the following way:

var obj = JSON.parse(data, function (key, value) {
  alert(key + " " + value) // will alert => "project_id 1"
}

I am trying to iterate using the main index ("1", "2" etc). How can I do this? I have a searched a lot but I didn't find any solution.

2 Answers

Using Object.keys might help you. This is a nested loop.. but works

let data = `{
    "1":[{"project_id":1,"project":"IET1"},{"project_id":2,"project":"IET2"}],
    "2":[{"project_id":3,"project":"IET3"}],
    "3":[{"project_id":4,"project":"IET4"},{"project_id":5,"project":"IET5"}]
}`;

data = JSON.parse(data)
const keys = Object.keys(data);

keys.forEach(key => data[key].forEach(project => console.log(project.project_id + " - " + project.project)));

Don't use the "reviver" call back function within JSON.parse() - that is used to transform the data as it is parsed.

Just parse it. then you can retrieve the keys if you want them or iterate over them using for in loop.

let data = `{
"1":[{"project_id":1,"project":"IET1"},{"project_id":2,"project":"IET2"}],
"2":[{"project_id":3,"project":"IET3"}],
"3":[{"project_id":4,"project":"IET4"},{"project_id":5,"project":"IET5"}]
}`;

const out = JSON.parse(data);

const keys = Object.keys(out);

for (key in out) {
  alert(out[key][0].project);
  console.log(key, out[key]);
}

Related