Solution 1 :

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>'
    );

});

Problem :

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>

Comments

Comment posted by Ryan

Thank you! I got it. But it only displays the last data in the object(item 3).

Comment posted by Ani

@Ryan Please check the code I have put above. I have added

Comment posted by Ryan

Thank you! I used $(“#cartList”).append instead of .html to display it. But the accessing of the counts solved this for me.

By