1

I would like to loop through a list of objects and display one property on a graph on the page but I can't seem to get the right syntax to get this data in a loop.

Without the loop this gives an idea of what I want to do:

document.getElementById("v1").innerHTML = zone1.sensor; 
document.getElementById("v2").innerHTML = zone2.sensor;
document.getElementById("v3").innerHTML = zone3.sensor;

I can't figure out how to loop through the objects, something like this:

for(i = 1; i < 7; i++) {
document.getElementById("v" + i).innerHTML = ("zone" + i + ".sensor");
}
Simon_A
  • 145
  • 2
  • 11
  • 2
    The zones should definitely be an array instead of individual variables, but other than that this is a duplicate of [JavaScript: Get local variable dynamically by name string](http://stackoverflow.com/questions/1920867/javascript-get-local-variable-dynamically-by-name-string) – JJJ Aug 31 '15 at 23:09
  • 1
    You have the wrong approach. Programming is about abstraction. You shouldn't have `zone1`, `zone2`, and `zone3`, but instead an array of objects: `var zones = []` – royhowie Aug 31 '15 at 23:11

2 Answers2

4

While that can be done with eval() or new Function (), that's just plain wrong. Put your values in an array and access them by index. If you absolutely have to use independent variables, do:

var arr = [zone1, zone2, zone3];

and then use

arr[i].sensor
Amit
  • 45,440
  • 9
  • 78
  • 110
0

I would go this way to avoid the use of eval:

var zone1 = new Object;
var zone2 = new Object;
var zone3 = new Object;

zone1.sensor = "sensor1";
zone2.sensor = "sensor2";
zone3.sensor = "sensor3";

var zones = [zone1, zone2, zone3];

for( var i = 1; i < 4; i++) {
  document.getElementById("v" + i).innerHTML = zones[i - 1]["sensor"];
}
<div id="v1"></div>
<div id="v2"></div>
<div id="v3"></div>

Hope it helps!

David
  • 6,695
  • 3
  • 29
  • 46