Similarly phrased questions have been posed here multiple times, but none seem to help me with my issue. I am working with JSON data pulled from an API (PokeAPI), and I've stored this data in an object in Javascript. As I understand it, this then stores the JSON data in an array, Console.log(myData) yields me the following in the Chrome console:
I want to build a table laying out some of the data in each of these objects in the array. I thought I could access any field in each object by simply using code such as myData[0].name, but this is failing. Attempting to execute Console.log(myData[0]) simply returns an undefined object. How can I access the data I want iteratively?
My current attempt looks as follows:
function getData(inputData) {
var data = [];
for (i = 0; i < inputData.length; i++) {
data[i] = [
inputData[i].id,
inputData[i].name,
inputData[i].height,
inputData[i].weight,
inputData[i].type[0],
inputData[i].base_experience];
}
console.log(inputData); //Returns all the data
console.log(inputData[0]); //Returns undefined
return data;
Edit: A couple comments asked to see how I fetched the data from the API. Here it is:
function fetchData(endpoint_URL) {
$.ajax({
url: base_URL + endpoint_URL,
dataType: "json",
success: function (response) {
//console.log(response);
let p = new Promise((resolve, reject) => {
successHandler(response);
if(dataSet != null) {
//console.log(dataSet);
resolve('Success');
} else {
reject('Failed');
}
})
//console.log(dataSet);
p.then((message) => {
//console.log(dataSet);
loadTableData(dataSet)
}).catch((message) => {
console.log("Data fetch unsuccessful");
})
},
error: function(request, status, error){
console.log(status);
}
});
function successHandler(response) {
dataSet = [];
interimData = [];
for (var i in response.results) {
interimData[i] = response.results[i];
//console.log(response.results[i]);
//console.log(dataSet[i]);
}
//console.log(interimData);
for (let i = 0; i<interimData.length; i++) {
$.ajax({
url: interimData[i].url,
dataType: "json",
success: function(details) {
dataSet[i] = details;
}
})
};
//console.log(dataSet);
};
The dataSet object is declared outside of any function (globally?) with the code var dataSet=[];. The getData() function is called in the first line of loadTableData()
for (var e of inputData) if (e !== undefined) console.dir(e)?getDatafunction with it?dataSetis declared globally asvar dataSet=[];, what's the rationale behind:dataSet != null? This won't ever be true.