Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object literal. object[i].variable

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!

like image 455
Cobradelaplaya Avatar asked Nov 01 '12 20:11

Cobradelaplaya


People also ask

What is an object literal JavaScript?

The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array. Values created with anonymous functions are methods of your object. Simple values are properties.

What is difference between object and object literal in JavaScript?

Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.

Is there a way to use variable keys in a JavaScript object literal?

ES6 defines 'ComputedPropertyName' as part of the grammar for object literals, which helps use a variable for a key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets. Syntax: var key="your_choice"; var object = {}; object[key] = "your_choice"; console.


2 Answers

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

plantaVariables[i] = parseInt(data[0][capitaliseFirstLetter(i)]);
like image 154
Ted Hopp Avatar answered Oct 19 '22 08:10

Ted Hopp


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

var string = capitaliseFirstLetter(i);
plantaVariables[i] = parseInt(data[0][string]);
like image 1
Rocket Hazmat Avatar answered Oct 19 '22 10:10

Rocket Hazmat