Reputation: 229
I have a JSON Object from my SessionStorage. I want to display them on my view.
Object:
0: {itemName: "Item 1", itemPrice: 0, itemQuantity: "1"}
1: {itemName: "Item 2", itemPrice: 0, itemQuantity: "1"}
2: {itemName: "Item 3", itemPrice: 0, itemQuantity: "1"}
What i tried so far is using JQuery to loop it but it displays Undefined.
JS:
var cartItems = JSON.parse(sessionStorage.cart);
$.each(cartItems, function(key, value) {
$("#cartList").html(
'<li class="list-group-item d-flex justify-content-between align-items-center d-flex justify-content-between w-100">' +
'<a>'+cartItems.itemName +'</a>' +
'<a>'+cartItems.itemQuantity+'</a>' +
'<span class="badge"><i class="material-icons large">keyboard_arrow_right</i></span>' +
'</li>'
);
});
HTML:
<div class="list-group list-group-flush" id="cartList">
</div>
Upvotes: 0
Views: 59
Reputation: 391
You are not accessing the values correctly inside the loop, it should be accessed as cartItems[key].itemName
. The code may look like,
$.each(cartItems, function(index, value) {
$("#cartList").html(
$("#cartList").html() +
'<li class="list-group-item d-flex justify-content-between align-items-center d-flex justify-content-between w-100">' +
'<a>' + cartItems[index].itemName + '</a>' +
'<a>' + cartItems[index].itemQuantity + '</a>' +
'<span class="badge"><i class="material-icons large">keyboard_arrow_right</i></span>' +
'</li>'
);
});
Upvotes: 1