This question already has an answer here:
How can I call an async function inside a jQuery .change function? I have tried the following and it returns me "undefined"...
async function getData(){
try {
return await $.getJSON('./data.json').promise();
} catch(error) {
console.log("error" + error);
throw error;
} finally {
alert("done");
}
}
Here an example of the JSON:
{
"stuff": {
"First": {
"FirstA": {
"year": [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
},
"FirstB": {
"year": [2007, 2008, 2009, 2010, 2011, 2012],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
}
},
"Second": {
"SecondA": {
"year": [2002, 2003, 2004, 2005, 2006],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
},
"SecondB": {
"year": [2007, 2008, 2009, 2010, 2011, 2012],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
}
}
}
}
And Here is the jQuery function:
$('select[name="make"]').change(function(){
// THIS LET RETURNS EITHER First or Second
let makeSelected = $('select[name="make"] option:selected').val();
getData().then(data => {
let topModels = data.stuff;
// THIS RETURNS UNDEFINED
console.log(topModels.makeSelected);
// THIS RETURNS THE CORRECT DATA
console.log(topModels.First);
});
});
How come the let variable does not work for the first console.log?
Everything should work fine, but you are acessing a property ("makeSelected") that doesn't exist on the "data.stuff". By using
data.stuff.makeSelected
that's what you're asking for. Now, if what you intent to do is to look for a property with the name equal to the value inside the variable "makeSelected", you have 2 main paths to choose from:1) Use "eval": You can build a string just like
let str = "data.stuff."+makeSelected; let result = eval(str);
2) You could use the
[]
notation to access an JS object properties, just likelet result = data.stuff[makeSelection];
which is my prefered solution.