简体   繁体   中英

How can I check whether an item exists in localstorage or not using pure javascript

在此处输入图片说明 I 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.

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM