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!

1
  • return data[0][string] Use [] instead of .. Commented Nov 1, 2012 at 20:46

2 Answers 2

6

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

plantaVariables[i] = parseInt(data[0][capitaliseFirstLetter(i)]);
Sign up to request clarification or add additional context in comments.

Comments

1

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

var string = capitaliseFirstLetter(i);
plantaVariables[i] = parseInt(data[0][string]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.