The issue is related to the extra double quotes " character in the products array in between the opening [ and the first { , as well as between the closing } and ] , this comes from the JavaScript variable called "products" being printed as a string.
So the question is how to get that variable to print without the surrounding double quotes?
let products = '';
for(var i=0; i<this.items.length; i++) {
products += "{";
products += "'name' : '" + this.items[i].info.brand + " " + this.items[i].info.title + "',";
products += "'id' : '" + this.items[i].info.sku + "',";
products += "'price' : '" + this.items[i].info.price + "',";
products += "'brand' : '" + this.items[i].info.brand + "',";
products += "'category' : '" + this.items[i].info.category + "',";
products += "'variant' : '" + this.items[i].info.color + "',";
products += "'quantity' : '" + this.items[i].quantity + "',";
products += "}";
if(i != (this.items.length - 1)){
products += ',';
}
console.log(products);
}
So when I print the products, you can see the entire products section is within double quotes. What I am trying to do is there should be no double quote before the opening bracket of the first product, and after the last bracket of the last product.
>Solution :
You probably are trying to build an object, in which case you should just use .map on this.items, e.g.:
function example() {
return { products: this.items.map((item) => {
return {
"name": item.info.brand + " " + item.info.title,
"id": item.info.sku,
"price": item.info.price,
"brand": item.info.brand,
"category": item.info.category,
"variant": item.info.color,
"quantity": item.info.quantity
};
})};
}
console.log(
example.bind({ items: [{info: { brand: "whirlpool", title: "dishwasher", sku: "123", price: "$140", category: "dishwashers", color: "white", quantity: 2}}]})()
)
