-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
  • 8

3 Answers3

2

You can do this:

var brand = 'ford';
$.each(data[brand], function(i, item) {....
palaѕн
  • 72,112
  • 17
  • 116
  • 136
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,709
  • 5
  • 44
  • 66
1

try this,

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