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!
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.
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.
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.
You should use subscript notation to look up an object attribute by expression:
plantaVariables[i] = parseInt(data[0][capitaliseFirstLetter(i)]);
Remember, objects can be referenced using []
, just like arrays.
var string = capitaliseFirstLetter(i);
plantaVariables[i] = parseInt(data[0][string]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With