Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javscript: No double quote before the opening bracket and after the last bracket

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.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}}]})()
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading