My scenario involves the existence of an object named productCounts
[{provisioned=2.0, product=str1, totalID=1.0},
{product=str2, provisioned=4.0, totalID=3.0},
{provisioned=6.0, product=str3, totalID=5.0}]
In addition, there is an array labeled uniqueProduct
[str1, str2, str3, str4]
The objective here is to iterate through a dataset in order to retrieve the count of totalID, then add it to the respective product's totalID. If the product does not exist, it should be included in the object.
var countID = 0;
uniqueProduct.forEach(
currentproduct => {
countID = 0;
for (var i = 0; i < shtRng.length; ++i) {
if (shtRng[i][ProductCol].toString() == currentproduct) { // && shtRng[i][IDcol].toString().length>4){
countID++;
}
}
if (countID == 0) {
return;
}
console.log(currentproduct + ": " + countID);
}
)
This code effectively returns the countID per product within uniqueProduct
Instead of just logging the outcome, the aim is to incorporate it into the object as shown below... when the current unique product is absent from the productCounts
object, it should be added accordingly.
let obj = productCounts.find((o, i) => {
if (o.product == currentproduct) {
productCounts[i] = { product: currentproduct, totalID: productCounts[i].totalID+countID, provisioned: productCounts[i].provisioned };
return true;
} else {
productCounts.push({ product: currentproduct, totalID: countID, provisioned: 0 });
return true;
}
});
Although theoretically sound, the execution seems to miss certain records or duplicates products. How can the object be updated accurately?
The anticipated outcome is for the object to resemble the following:
[{provisioned=2.0, product=str1, totalID=35.0}, {product=str2, provisioned=4.0, totalID=8.0}, {provisioned=6.0, product=str3, totalID=51.0}, {provisioned=6.0, product=str4, totalID=14.0}]