-5

I'm having some trouble understanding what bit of Javascript to use to loop through the below object to then output into HTML. The aim is to output the values from the object on to the page something like the HTML Output.

{
   "lineItems":{
      "physicalItems":[
         {
            "id":70,
            "productId":362,
            "name":"Sample Product 1 ",
            "sku":"290909",
            "quantity":1,
            "isTaxable":true,
            "discounts":[

            ],
            "discountAmount":0,
            "listPrice":130,
            "salePrice":130,
            "extendedListPrice":130,
            "extendedSalePrice":130,
            "extendedComparisonPrice":130,
            "categories":[

            ],
            "type":"physical",
            "variantId":593
         },
         {
            "id":69,
            "productId":383,
            "name":"Sample Product",
            "sku":"280910",
            "quantity":1,
            "isTaxable":true,
            "discounts":[

            ],
            "discountAmount":0,
            "listPrice":350,
            "salePrice":350,
            "extendedListPrice":350,
            "extendedSalePrice":350,
            "extendedComparisonPrice":350,
            "categories":[

            ],
            "type":"physical",
            "variantId":685
         }
      ],
      "digitalItems":[

      ],
      "giftCertificates":[

      ]
   }
}

HTML Output Required

PhysicalItems 1 - Sample Product 1
SalePrice 1 - 130
PhysicalItems 2 - Sample Product
SalePrice 2 - 350

Any help on this would be appreciated. Thanks

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51

1 Answers1

1

Your cleanest options would be to use a templating framework like mustache.js or handlebarsjs.

However, with ES6 JavaScript you can do something like this:

const lineItems = require("./lineItems.json");

/**
* @param {string} type
*/
const createMarkupFor = type => {

const markup = `
   <ul>
       ${lineItems[type].map((lineItem, index) => (`
            <li>
                PhysicalItems ${index + 1} - Sample Product ${lineItem.name}
             </li>
             <li>
                SalesPrice ${index + 1} - ${lineItem.salePrice}
             </li>
        `))}
    </ul>`
    
    document.body.innerHTML = markup;
};

createMarkupFor("physicalItems");
Frank Waalkens
  • 261
  • 3
  • 5