0

I have trouble accessing object' property in the example below. On the third line I'd like to have the number 42 replaced with the value of the variable devNumTemp, but so far I'm not successfull.

What is the proper way to do this? I've tried several options, but never getting any further than getting undefined.

function getTempDev(devNumTemp, devNumHum, id, description){
  $.getJSON("http://someurl.com/DeviceNum=" + devNumTemp,function(result){
  var array = result.Device_Num_42.states;
  function objectFindByKey(array, key, value) {
   for (var i = 0; i < array.length; i++) {
     if (array[i][key] === value) {
     $("#id").html(description + "<div class='right'>" + array[i].value + "&deg;C" + "&nbsp;&nbsp;&nbsp;(" + someVariable + "%" + ")" + "<br></div>");
     }
     }
   };
   objectFindByKey(array, 'service', 'something');
   });
};
1
  • You mean replaced by the value of devNumTemp? Commented Oct 31, 2014 at 13:47

1 Answer 1

1

You can acces to object's properties like this

var array = result["Device_Num_" + devNumTemp].states;

It's considered a good practice to test for field's existance before trying to access it:

    var array = [];
    if (result && result["Device_Num_" + devNumTemp]){
        array = result["Device_Num_" + devNumTemp].states;
    }

This way we prevent Null Pointer Exception type errors.

Sign up to request clarification or add additional context in comments.

1 Comment

Im going to try that as soon as Im back at my terminal. Thanks for your very quick answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.