-1

enter image description hereI have a project on pure javascript,and I was working on saving items to localstorage. I only need to save id, name and image of the item i am saving.

My major problem , however is i do not want save duplicate .Therefore before i save i must check whether the exists or not.

I have so far tried several approaches but all seems not to work.Below is my code snippets.

I am able to save item to localstorage with no problems, infact i can save and delete items from localstorage correctly.

const cart_DB = new cartDB();

if( cart_DB.isAddedToCart(cartInfo.id) === false) {

    // save item to database

}else {
    alert('item already in cart');
    return false;
}
class cartDB {



            /// save cart into localstorage ////
            saveIntoDB(cart) {
                const carts = this.getFromDB();

                carts.push(cart);

                // add the new array into localstorage
                localStorage.setItem('carts', JSON.stringify(carts));
            }
            /// save cart into localstorage ///



            /// return carts from storage ///
            getFromDB() {
                let carts;

                // check from local storage
                if (localStorage.getItem('carts') === null) {
                    carts = [];
                } else {
                    carts = JSON.parse(localStorage.getItem('carts'))
                }

                return carts;

            }
            /// carts from storage ends ///

        /// check if item already exists in database //////// 
    isAddedToCart(id) {

    if (localStorage.getItem(id) === null 
            ||localStorage.getItem(id).length === 0) {
                      return false;
                        }else {

                      return true;
                        }
            }
      //// checking items ends here ///////

}

What i want is to check whether the item exists or not before adding another item.

Seyyid Said
  • 475
  • 2
  • 6
  • 16

2 Answers2

2

Assuming that you store items in array you can use below function to check if item already exists:

function checkIfItemExists (id) {
  const items = localStorage.getItem('carts') 
  let itemExists = false
  if (items) {
    const itemsData = JSON.parse(items)
    // check if item with given id exists in local storage data
    itemExists =  itemsData.find(item => item.id === id)
  }

  return itemExists
}
Bartek Fryzowicz
  • 6,464
  • 18
  • 27
  • Pretty lazy answer.. Just a helper function you copied, not answering the question. – Wimanicesir May 20 '19 at 09:50
  • Firs of all it's not copied. Secondly it shows how to check if item with given id exists in array returned from local storage so it answers thr question. – Bartek Fryzowicz May 20 '19 at 09:51
  • It checks if given id exists in localstorage with items. Which was nowhere to be found, after edit it is suddenly carts. It's ok to copy code to help people, just check if it fully answers their question. – Wimanicesir May 20 '19 at 09:54
  • Yes, I've changed 'items' to 'carts' becuase OP edited his code so I had to update my answer also. – Bartek Fryzowicz May 20 '19 at 09:55
  • 1
    Sorry, I guess I came just in after OP had editted and you didn't. At that point it looked weird. Upvotted because answer is correct :) – Wimanicesir May 20 '19 at 09:58
0

If your goal is to find out if there's a duplicate, Array.some() would be the best function you are looking for. Implement it to your function like this.

isAddedToCart(id) {
    const carts = localStorage.getItem('carts');
    return carts.some(cart => cart.id == id);
}

Array.some() Definition and Usage

The some() method checks if any of the elements in an array pass a test (provided as a function).

The some() method executes the function once for each element present in the array:

  • If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining values)

  • Otherwise it returns false

JkAlombro
  • 1,696
  • 1
  • 16
  • 30