简体   繁体   中英

How to dynamically access object's property?

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');
   });
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM