skip to Main Content

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.

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

2

Answers


  1. 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]);
      }
    
    Login or Signup to reply.
  2. Object.keys(res.Employee).forEach(function (name) {
        if (Data1[0].empName == name) {
            console.log(res.Employee[name][0]);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search