Home > Software engineering >  Javascript access json data inside loop
Javascript access json data inside loop

Time:01-07

I have json data, now I'm trying to access it inside loop. But I got undefined.

Is there any way how to access it from loop?

var list = {
  macAddress: 'C0:49:EF:D3:79:20',
  category: 'esd',
  dr1: 1,
  dr2: 1,
  dr3: 0,
  dr4: 0
}

console.log(list);

for(var i=1; i<=2; i  ) {
  var pinName = "dr"   i;
  
  console.log(list.pinName);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

List has no property pinName. You need the value of pinName to be evaluated as the key by calling list[pinName].

CodePudding user response:

Here, the pinName variable is being treated as a string, rather than as a property name. To access the properties of the list object using a variable, you can use the square bracket notation, like this:

for(var i=1; i<=2; i  ) {
  var pinName = "dr"   i;
  
  console.log(list[pinName]);
}

This will access the properties of the list object using the value of the pinName variable as the property name. In the first iteration of the loop, this will be equivalent to list.dr1, and in the second iteration it will be equivalent to list.dr2.

Alternatively, you can use the Object.keys() method to loop through the properties of the list object, like this:

for (var key of Object.keys(list)) {
  console.log(list[key]);
}

Hope it helps.

  • Related