简体   繁体   中英

JQuery/Javascript - Reference object using variable name

Please excuse my inability to accurately describe what it is I am after. This in ability has made it very difficult to search for an answer, thus I am asking now.

I have an object (data.drivers) which contains a bunch of lap information.

I am looping through this object to update already displayed information, but would like to condense my code and be able to loop through the fields rather than write the same code for every possible field.

Problem is I do not know how to get the value from i by refering to it with a variable. For example:

$.each(data.drivers, function(pos, i) {
  var driver_position = i.position;  // this and much more would happen for 9 fields
  alert (driver_position);
});

This works.

But what I would like to do is this:

$.each(data.drivers, function(pos, i) {

  var fields = [ 'position', 'name', 'laps', 'lapTime', 'pace', 'difference', 'elapsedTime', 'fastLap', 'eqn' ];

  $.each (fields, function (ii, field) {
    alert (i.field);
  });

});

What you're looking for is bracket notation:

alert(i[field]);

Though using some more descriptive variable names helps in the long run, quite a bit.

You could also just loop over properties with each as well. You don't need that fields array of properties unless there are only specific properties you need and even then you can handle it within the each .

// Loop over array of driver objects
$.each(data.drivers, function(index, driver) {
    // Loop over driver object properties
    $.each(driver, function(key, value) {
        // key is property name
        // value is property value
    });
});

Documentation: http://api.jquery.com/jquery.each/

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

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