'Trouble with JavaScript 2D array and nested loop
Will you please explain what I'm missing? And possibly what I can do to fix it. I'm receiving the error: TypeError: Cannot set properties of undefined (setting '0') while trying to add data to this 2D array.
wixData.query("paidLineItems").eq("paidOrderId", orderNumber).find().then((result)=>{
let nbrRecs = result.totalCount
let newOrder = [];
matrix = new Array(nbrRecs).fill(0).map(() => new Array(8).fill(0));
for (var i = 0; i < nbrRecs; i++) {
let lineItem = result.items[i];
if (result.items[i].prodQty > 1) {
let qty = result.items[i].prodQty
while (multipleLineCtr < qty) {
matrix[multipleLineCtr][0] = lineItem.email
matrix[multipleLineCtr][1] = lineItem.prodName
matrix[multipleLineCtr][2] = lineItem.prodQty
matrix[multipleLineCtr][3] = multipleLineCtr
matrix[multipleLineCtr][4] = "Jesus"
matrix[multipleLineCtr][5] = lineItem.paidOrderId
matrix[multipleLineCtr][6] = lineItem.purchaseDt
matrix[multipleLineCtr][7] = lineItem.dtSupportEnds
multipleLineCtr++;
}
}else {
matrix[cnt][0] = lineItem.email
matrix[cnt][1] = lineItem.prodName
matrix[cnt][2] = lineItem.prodQty
matrix[cnt][3] = 1
matrix[cnt][4] = "Jesus"
matrix[cnt][5] = lineItem.paidOrderId
matrix[cnt][6] = lineItem.purchaseDt
matrix[cnt][7] = lineItem.dtSupportEnds
cnt++;
}
}
})
.catch((error) => {
console.log(error);
});
});
Solution 1:[1]
You should check if the matrix[index]
is an array or not, and if it is, you should create an array at matrix[index]
.
matrix[multipleLineCtr] ||= [];
or the traditional way:
if (!Array.isArray(matrix[index])) {
matrix[index] = [];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniel Dez |