I try to write script to loop through object and return those which type is equal to custom data type set in HTML. Yet im unable to pass variable with array of objects to my for loop. Can you please tell me what am I doing wrong in this code? I receive:
Cannot read property 'length' of undefined
PS. It has to be done in raw JavaScript, no jQuery
var btn = document.getElementById("btn");
var przepisy;
function findData(data) {
var kuchnia = data.dataset.type;
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function() {
if (this.readyState === 4 && this.status == 200) {
przepisy = JSON.parse(myRequest.responseText);
}
};
myRequest.open('GET', 'js/przepisy.json');
myRequest.send();
for (i = 0; i < przepisy.length; i++) {
var results = "";
var obj = przepisy[i];
var type = przepisy.type;
if (type === kuchnia) {
results += obj.name;
document.write(results);
}
}
}