TL;DR
Object.entries
provides exact the output you're trying to create there:
let row = Object.entries(supplies.food);
Details, and why your code isn't working
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);