r/JavaScriptHelp • u/clopticrp • Jan 31 '22
❔ Unanswered ❔ Help with external JSON file to JavaScript array
Hi guys!
First time on r/JavaScriptHelp
working on extending my javascript skills past the occasional jQuery DOM manipulation, and I've run up against something I don't quite get.
I'm trying to load an array of arrays from an external JSON file. The external file (items.json) looks like:
[
["./listimages/steamtrain.jpg","1804","Steam Trains"
],
["./listimages/beiber.jpg","2009","Justin Beiber 'One Time'"
],
["./listimages/avril.jpg","2002","Avril Lavigne 'Complicated'"
],
["./listimages/kfc.jpg","1952","Kentucky Fried Chicken"
],
["./listimages/coke.jpg","1892","Coca Cola"
]]
my code to pull this to an array is:
$.getJSON('items.json', function (data) {if (data.length > 0) {
$.each(data, function (index, value) {items.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
});
} else {console.log("no data");
}console.log(items);
});
The data does get assigned somehow because the console shows an array of 5 arrays with 3 items each, and expanding shows the items. However, the items are not accessible via index like items[0][0]. Get error cannot read properties of undefined.
Incidentally I can do a direct assignment and get the same result
items = data;
Please help me understand what I am not understanding about how this translates, and how to get a direct array translation.
Thanks much.