Reputation: 1027
I have a for loop in JavaScript like
var loopvariable = 0;
let row = [[]];
for (var key in supplies.food) {
row[loopvariable][0] = key;
row[loopvariable][1] = supplies.food[key];
loopvariable++;
}
why am i getting the following error
TypeError: row[loopvariable] is undefined
Upvotes: 2
Views: 858
Reputation: 1074355
Object.entries
provides exact the output you're trying to create there:
let row = Object.entries(supplies.food);
You've only created an array at row[0]
, not at row[1]
(row[2]
, row[3]
, ...), but then you're trying to use an array at row[1]
on the second iteration of the loop.
The minimal change is to leave the creation of the inner arrays to the loop body:
var loopvariable = 0;
let row = []; // ***
for (var key in supplies.food) {
row[loopvariable] = []; // ***
row[loopvariable][0] = key;
row[loopvariable][1] = supplies.food[key];
loopvariable++;
}
But we can also use an array initializer to be more concise:
var loopvariable = 0;
let row = [];
for (var key in supplies.food) {
row[loopvariable++] = [
key,
supplies.food[key]
];
}
But, again, for this specific case you can just use Object.entries
:
let row = Object.entries(supplies.food);
Live Example:
const supplies = {
food: {
water: "3l",
bread: "2 loaves",
chocolate: "4 bars"
}
};
let row = Object.entries(supplies.food);
console.log(row);
Object.entries
is supported in all modern environments, and easily polyfilled in older environments.
In a comment you've said supplies.food
is an array. If so, for-in
isn't the right way to loop through it (see this answer for details), but Object.entries
still works because arrays are objects, too (see my blog post for more):
const supplies = {
food: [
"3l water",
"2 loaves bread",
"4 bars chocolate"
]
};
let row = Object.entries(supplies.food);
console.log(row);
Upvotes: 4
Reputation: 386600
The variable
row[loopvariable]
is not initialized. You could use a default value and take an array with a guard operator (logical OR ||
).
row[loopvariable] = row[loopvariable] || [];
A shorter approach could be just to push a new array to row
, without using an aditional variable loopvariable
let row = [];
for (var key in supplies.food) {
row.push([key, supplies.food[key]]);
}
Upvotes: 4