Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate over Json object in javascript or Ecmascript?

I have this json Response and having difficulty in iterating over this json structure.The idea is to print the numbers written within the square brackets if they match with "Data" Json which is another json object. Like in this case 6099 should print.

Response and Data

var Response = {
  "Employee" : {
    "John" : [ "6131" ],
    "Alex" : [ "402537" ],
    "Mary" : [ "6039" ],
    "Java" : [ "6039" ],
    "Anna" : [ "6099" ]
}
}

var Data = [
  {
    "empName": "Anna"
}
]

I tried with forEach but because Response is not an array or set so it was not working and giving error that "Response.employee.forEach is not a function" and couldnt understand how to iterate on json objects.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var Data1 = JSON.parse(Data) 
var res= JSON.parse(Response)

res.Employee.forEach(function(res1) {
    var test = res1
        if(Data1.empName== test){
        console.log(test[0])
        }
});

Expected Output should be : 6099

>Solution :

You can use a for…in loop for example to iterate over the keys then, you can check if the current key matches the empNamee. If it does, you can print the number in the square brackets:

var dataName = Data[0].empName;
for (var key in Response.Employee) {
  if (key === dataName) {
    console.log(Response.Employee[key][0]);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading