Code Cannibal
Code Cannibal

Reputation: 27

Using a javascript array to request data from a JSON file

I was wondering if it's possible to request data from a JSON file (For example: customers.name). But instead of that using an array containing the JSON object names and looping it. My code is below.

function load(url ,callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', url, true);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == 200) {
            callback(xobj.responseText);
        }
    };
    xobj.send(null);
}

load("klanten.json", function(response) {
    var klanten = JSON.parse(response);
    //Array containing JSON file object names.
    var infArray = ['name', "address", "email", "phone", "place", "zip"];
    //Calling said info using a for loop.
    for(var i = 0; i < infArray.length; i++) {
      console.log(klanten[i].infArray[i]);
      //It not working for some reason.
    }
});

I`d love some help with this. And in case what im asking is completely stupid, also let me know! Any help is welcome, thanks!

Upvotes: 0

Views: 72

Answers (1)

EladBash
EladBash

Reputation: 95

Change console.log(klanten[i].infArray[i]); to:

console.log(klanten[i][infArray[i]]);

Upvotes: 2

Related Questions