When I add the brackets around the object I can not seem to grab the year. If I remove the brackets I can access the year value by writing:
var a = car.year;
console.log(a); // 2000, 2020
I think this is a syntax issue on my part but haven’t been able to figure out how to get the value only for each object.
Is there a way that for each loop you can store the year for each object in the array in a variable? Again, this works if I only have one object. But if I add multiple objects to the car variable and add brackets, I can no longer access the value by using
When you have them in an array, forEach has each object as the first function parameter.
I find that it helps to use plural for arrays, so that the singular term can be used without confusion as the loop parameter. Here, that means using plural cars and singular car.
I get undefined when I change the car variable to cars. Here’s sample code: Pulled some from the SitePoint blog post. Call JS function string without using eval Essentially, I am storing a function name in the car object and then am needing to extract the string which is then used in a switch statement to determine which function to call. So if there are 5 different objects then there would be 5 function calls using the year value for each.
function extractYearValue(car) {
for (const [key, value] of Object.entries(car)) {
var fnstring = car.year;
switch (fnstring) {
case "2020": carFuncA(); break;
case "2000": carFuncB(); break;
}
}
}
And, parameter destructuring (also called parameter context matching) can be used, so that we can more explicitly state that we want only certain values from the object being given to the function.