Reputation: 229
I have object data in sessionStorage and I want to display them as a list in HMTL via loop. How do I Achieve this?
SesionStorage.cart data stringified:
[{"itemName":"WS: FaceShield, 10pcs pack","itemPrice":0,"itemQuantity":"1"},{"itemName":"Faceshield, 1 pc","itemPrice":0,"itemQuantity":"1"}]
What I want to do now is display them on a list after parsing them as JSON Object again.
Upvotes: 1
Views: 201
Reputation: 206151
Say you have
<ul id="myUL"></ul>
Here's a suggestion how to do it in JavaScript by using Array.prototype.reduce into a Web API DocumentFragment that can be later ParentNode.append() -ed into an UL
HTMLElement:
// Let's define our array
const arr = [
{"itemName":"WS: FaceShield, 10pcs pack","itemPrice":0,"itemQuantity":"1"},
{"itemName":"Faceshield, 1 pc","itemPrice":0,"itemQuantity":"1"}
];
// Store it into LS...
localStorage.arr = JSON.stringify(arr);
// Read it from LS
const LS_arr = JSON.parse(localStorage.arr);
// Create a helper for new elements...
const ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});
// Loop the array and create LI elements
const LIS = LS_arr.reduce((DF, item) => {
DF.append(ELNew('li', {
textContent: `Name: ${item.itemName} Price: ${item.itemPrice}`
}));
return DF;
}, new DocumentFragment());
// Once our DocumentFragment is populated - Append all at once!
document.querySelector("#myUL").append(LIS);
Upvotes: 1