So I’m trying to print out only the year data because I want to perform some functions on it. the q var is coming form a html form so we don’t know what will be the value of q the user will decide:
filtered: [
{ Year: '2019', score1: 88 },
{ Year: '2020', score1: 89 },
{ Year: '2021', score1: 90 },
{ Year: '2022', score1: 91 },
{ Year: '2023', score1: 92 },
{ Year: '2023', score1: 100 }
]
var q = "Year";
for (let i = 0; i < filterd.length; i++) {
console.log(filterd[i].q);
}
Output:
undefined
undefined
undefined
undefined
undefined
undefined
2
Answers
From the link I’ve added in the comment
Here is your snippet fixed:
The reason your code did not work was because in each iteration of the loop, your code was looking for a property called
q
in each object of your filtered array, as opposed to what you wanted, which wasfiltered[i]."Year"
. This wouldn’t work the way you would want it to anyway, as a string here would be a syntax error.As far as I’m aware, the only way to insert a variable into an object property call is to use the
[]
notation, which accepts a string to target an object property. So in each iteration of the loop in the previous snippet, what is actually being read isfiltered[i]["year"]
, which is valid syntax.Now this works, but if the object is within your control, I would recommend sticking to property names that do not require the
[]
syntax, and in-fact, you do not need to do this in your example. Also, you can make the code more readable. Consider the following snippet instead:In this example, you remove the need for the
[]
property call syntax and storing the"year"
string in a variable by calling the property directly in the loop.Additionally, you have a more readable
for...of
loop statement for targeting each object in the array, as opposed to one of those ancientfor (i, condition, iteration)
loops.If your not too attached to either
var
orconst / let
, I would just stick to always usingconst / let
, as its more consistent with "modern" JavaScript.To learn about anything talked about here, MDN is (as always) the best place to start when learning anything web-dev. Here are some useful links relevant to what was talked about here:
Hope this helps.