I am using ngx chart library to display a barchart. It works fine when I use a static array but when I try to populate it dynamically, it does not work.
Below are my codes:
Note: allProducts is an array returned from API with a list of itemName, AmountPaid, Date purchased, etc. I only need the array below with itemname and amountpaid to populate a bar chart using ngxChart.
When I use this static array, everything works fine:
this.products = [{
"name": this.allProducts[0].itemName,
"value": this.allProducts[0].AmountPaid
},
{
"name": this.allProducts[1].itemName,
"value": this.allProducts[1].AmountPaid
}
,
{
"name": this.allProducts[2].itemName,
"value": this.allProducts[2].AmountPaid
}
,
{
"name": this.allProducts[3].itemName,
"value": this.allProducts[3].AmountPaid
}
,
{
"name": this.allProducts[4].itemName,
"value": this.allProducts[4].AmountPaid
}
,
{
"name": this.allProducts[5].itemName,
"value": this.allProducts[5].AmountPaid
}
];
When I try to create it dynamically as below - it does not return the array in the correct format:
this.allProducts.forEach((item) => {
this.productData.push({
"name": item.itemName,
"value": item.grossAmountPaid
});
})
The console.log for the static array returns the below - correct format:
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {name: "Car-SL-Monthly", value: 1000000}
1: {name: "Car-SL-Yearly", value: 1000000}
2: {name: "Car-RB-Monthly", value: 5000}
3: {name: "dsaf", value: 455}
4: {name: "Delivery Van", value: 500000}
5: {name: "Lorry", value: 1000000}
length: 6
__proto__: Array(0)
The dynamic array returns the below - Incorrect Format:
Array(6)
0: {name: "Car-SL-Monthly", value: 1000000}
1: {name: "Car-SL-Yearly", value: 1000000}
2: {name: "Car-RB-Monthly", value: 5000}
3: {name: "dsaf", value: 455}
4: {name: "Delivery Van", value: 500000}
5: {name: "Lorry", value: 1000000}
length: 6
__proto__: Array(0)
What is wrong with my foreach loop and how can I get my dynamic array (using foreach) to be in the same format as the static array?