2

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 2

2

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)));
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

one thing I wanna to ask more that how can I get the project_id, project etc in an alert?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.