The challenge you are facing appears to be related to how you have structured your data storage. To address this, the first step is to ensure that the array of products is indeed an array:
const products = [
{
id: item1,
name: 'My product',
price: 100
}, //...
];
Furthermore, what is the meaning or value of the item1
identifier? Is it a specific ID, perhaps an integer, used to uniquely identify each product?
To manage the "order state", consider creating an object that contains an array of references to the individual products like so:
const orderState = {
products: [
{
productID: item1,
quantity: 1
},
{
productID: item2,
quantity: 2
}
]
}
This restructured data model allows for easier manipulation and processing. Depending on the tools at your disposal, such as template engines, there are various methods to generate output. As an illustration, here's a simple logic to construct a string output:
var output = '<ul>';
for (var i = 0; i < orderState.products.length; i++) {
var product = {};
for (var j = 0; j < products.length; j++) {
if (products[j].id == orderState.products[i].id) {
product = products[j];
break;
}
}
output += '<li>' + product.name + ' x' + orderState.products[i].quantity + ' = $' + (product.price * orderState.products[i].quantity) + '</li>';
}
output += '</ul>';
As needed, you can refactor and enhance this approach. For instance, consider abstracting out the logic to find a product based on its id
into a separate function or utilizing built-in JavaScript functions or frameworks for streamlined operations. Keeping your data structures well-organized simplifies the coding process significantly.