-1

For example, I have a json file with cars from Ford and Volkswagen. Now I have a var where 'ford' or 'volkswagen' is stored. How can I use this var in combination with the data selection.

$.getJSON('file.json', function(data) {
    $.each(data.ford, function(i, item) {
        //do something      
    });
});


$.getJSON('file.json', function(data) {
    $.each(data.volkswagen, function(i, item) {
        //do something      
    });
});

I mean something like

var brand = 'ford';
data.+brand
k.j.
  • 39
  • 1
  • 7

3 Answers3

2

You can do this:

var brand = 'ford';
$.each(data[brand], function(i, item) {....
palaѕн
  • 68,816
  • 17
  • 108
  • 129
1

You can access that item in the object by using something like:

var brand = 'ford';
data[brand];

You can read more here on dot and square bracket notation.

Community
  • 1
  • 1
Jamie Taylor
  • 4,661
  • 5
  • 42
  • 62
1

try this,

 var brand = 'ford';
    $.getJSON('file.json', function(data) {
      $.each(data[brand], function(i, item) {
        //do something      
      });
    });
Anand Jha
  • 9,806
  • 6
  • 22
  • 28