5

I have a function where I get some JSON, and then extract the first element, based on some info in an object literal.

My problem is:

function foo(string){
return data[0].string;
}

This does not work. What is the correct syntax?

The full code is:

 var plantaVariables = {
    humidity : 0,
    airTemp : 0,
    soilTemp : 0,
    soilMoisture: 0,
    light: 0
  };

  function capitaliseFirstLetter(string){
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  for (var i in plantaVariables) {
    $.ajax({
      url: "http://xxx/"+i.toLowerCase(),
      dataType:"json",
      async: false,
      success: function(data){
        var string = capitaliseFirstLetter(i);
        plantaVariables[i] = parseInt(data[0].capitaliseFirstLetter(i));
      }
      });
  };

The JSON i get looks like this:

[{"PlantId":"1","DateTime":"2012-11-01 13:56:23","Humidity":"37.4"}]

(with more objects). And similar for any other element in the plantaVariables

I realize that this is a newbie question, but I am new to javascript, and I have banged my head against the screen all day. Any help would be very much appreciated!

2 Answers2

6

You should use subscript notation to look up an object attribute by expression:

plantaVariables[i] = parseInt(data[0][capitaliseFirstLetter(i)]);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

Remember, objects can be referenced using [], just like arrays.

var string = capitaliseFirstLetter(i);
plantaVariables[i] = parseInt(data[0][string]);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337