Home > database >  Array from JSON not populating
Array from JSON not populating

Time:11-20

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 >
        <img  src="images/sofas/freud-sofa-1.jpg"
          alt="Camel coloured, corduroy Freud sofa">
        <div  id="">
          <input  type="checkbox" id="checkboxFreud" value="" aria-label="...">
          <label  for="checkboxFreud">
            <h3 >Frued Sofa</h3>
          </label>
          <label  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 >56 988.00</span> (incl. VAT)<i
                ></i></p>
          </label>
        </div>
      </div>
    </div>

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

CodePudding user response:

If I'm reading these the functions correctly, and to piggy back off of @Randy Casburn's answer, you may want to try using .text() instead of .html() to get the price value. If the the price elements are inputs, however, you'll likely want to use .value() instead.

CodePudding user response:

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();
});
  • Related