-3

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

3
  • 1
    res.Employee[Data[0].empName][0]
    – cmgchess
    Commented May 4, 2023 at 10:42
  • @cmgchess No need to use loop?
    – Mayo
    Commented May 4, 2023 at 10:44
  • no need since object values can be directly accessed using a key unlike arrays
    – cmgchess
    Commented May 4, 2023 at 10:44

1 Answer 1

-2

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.