0

I need to loop through a series of values from a json array. I can explicitly name the object I want to sum but when I pass it a string parameter it won't work.

My code below:

var tot = 0
var category = "arson_15"
for(var i = 0; i < dc_nbh.features.length; i++) {

    tot = tot + Number(dc_map.features[i].properties.category);
}
 console.log(tot);

This returns "NaN" but when I change it to the code below it summs the values correctly:

var tot = 0

for(var i = 0; i < dc_nbh.features.length; i++) {

    tot = tot + Number(dc_map.features[i].properties.arson_15);
}
 console.log(tot);

why can't I pass a string var to the loop?

Asons
  • 84,923
  • 12
  • 110
  • 165
user2907249
  • 839
  • 7
  • 14
  • 32
  • 3
    `dc_map.features[i].properties[category]` – Pointy Apr 15 '16 at 16:09
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – Chris Apr 15 '16 at 16:10
  • For future reference, have you checked what the value of `dc_map.features[i].properties.category` is? This is a very common kind of bug in JS so understanding how to debug it is very beneficial. – Mike Cluck Apr 15 '16 at 16:10

0 Answers0