-1

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

});

2 Answers 2

1

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.

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

1 Comment

Precisely what I was after. Thank you.
1

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.

2 Comments

Wicked. Thanks for adding this - I was so caught up in my solution I didn't even see this possibility.
No problem. Good luck! =]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.