Here is your snippet fixed:
const 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 },
];
const q = 'Year';
for (let i = 0; i < filtered.length; i++) {
console.log(filtered[i][q]);
}
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 was filtered[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 is filtered[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:
const 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 },
];
for (let value of filtered) {
console.log(value.year);
}
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 ancient for (i, condition, iteration)
loops.
If your not too attached to either var
or const / let
, I would just stick to always using const / 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.