Search code examples
javascriptjqueryarraysjson

Array from JSON not populating


I am trying to add items to an array that is stored to sessionStorage. The add function is supposed to check if the there is a matching value in the array and if so, add to the count of that item. If not, it should push the item onto the array.

For some reason the two functions work perfectly fine on their own but when combined in an if/else statement it either doesn't push the item onto the array or it adds to the count AND pushes a duplicate to the array.

I tried two different methods.

I'm new to JavaScript and jQuery and will appreciate any insight.

Method one:

$(".prodItem").on("click", ".addCart", function (e) {

cart = JSON.parse(sessionStorage.getItem('shopCart'));


let selectedProd = $(e.target).closest('.prodItem').find('.prodName').html();
console.log(selectedProd);
let selectedPrice = $(this).siblings('.price').html();
console.log(selectedPrice);
let count = 1;



$.each(cart, function (index, value) {
        if (selectedProd === value.prod) {
            value.count++;
            console.log(selectedProd);
            console.log(value.prod);
            storeCart();
            return;
        }
    });
    if ($.inArray(selectedProd, cart) !== -1) {
        // Add new product object to array
        let currentProd = new product(
            selectedProd,
            count++,
            selectedPrice);
        cart.push(currentProd);
    }

// Save array to sessionStorage
storeCart();
});

Method two:

$(".prodItem").on("click", ".addCart", function (e) {

cart = JSON.parse(sessionStorage.getItem('shopCart'));


let selectedProd = $(e.target).closest('.prodItem').find('.prodName').html();
console.log(selectedProd);
let selectedPrice = $(this).siblings('.price').html();
console.log(selectedPrice);
let count = 1;

for (let i = 0; i < cart.length; i++) {
    if (selectedProd === cart[i].prod) {
        value.count++;
        console.log(selectedProd);
        console.log(value.prod);
        storeCart();
        return;
    } else {
        let currentProd = new product(
            selectedProd,
            count++,
            selectedPrice);
        cart.push(currentProd);
    }
}
// Save array to sessionStorage
storeCart();

});

The HTML:

<div class="col-4 prodimg prodItem">
      <div class="card bg-light text-white rounded-circle shadow">
        <img class="card-img rounded-circle shadow" src="images/sofas/freud-sofa-1.jpg"
          alt="Camel coloured, corduroy Freud sofa">
        <div class="card-img-overlay crdimg" id="">
          <input class="form-check-input d-none" type="checkbox" id="checkboxFreud" value="" aria-label="...">
          <label class="card-title form-check" for="checkboxFreud">
            <h3 class="prodName">Frued Sofa</h3>
          </label>
          <label class="card-text form-check" for="checkboxFreud">
            <p>This piece is the perfect fit to liven up any space.<br>A comfortable six-seater with durable
              corduroy upholstery.<br><br>R<span class="price">56 988.00</span> (incl. VAT)<i
                class="btn bi bi-cart-plus ml-4 addCart"></i></p>
          </label>
        </div>
      </div>
    </div>

**NOTE: The empty cart array is created and stored before this section.


Solution

  • The answer was actually quite simple and I found it here:

    I declared a boolean before running my $.each statement and then changed it if the product is found. The code now looks like this.

    $(".prodItem").on("click", ".addCart", function (e) {
    cart = JSON.parse(sessionStorage.getItem('shopCart'));
    cart = cart != null ? cart : [];
    
    let selectedProd = $(e.target).closest('.prodItem').find('.prodName').text();
    console.log(selectedProd);
    let selectedPrice = $(this).siblings('.price').text();
    console.log(selectedPrice);
    let count = 1;
    
    let currentProd = new product(
        selectedProd,
        count,
        selectedPrice);
    
    console.log($.type(cart));
    
    let exists = false;                   <-- declare boolean
    
    $.each(cart, function (index, value) {
            console.log($.type(cart));
            if (selectedProd === value.prod) {
                value.count++;
                console.log(selectedProd);
                console.log(value.prod);
                exists = true;            <-- change boolean
                storeCart();
            }
        });
    if(!exists) {                         <-- check boolean
        cart.push(currentProd);
    }
    
    // Save array to sessionStorage
    storeCart();
    });