Skip to content
Advertisement

How to avoid getting duplicated elements on localstorage array

i have the following code that generates a new element on an array in my localstorage each time i click on a button

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
    let button = addCartItemButtons[i]
    button.addEventListener('click', function(event){
        let buttonClicked = event.target
        let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
        let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
        let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
        let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
        let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
        let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
        let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
        let newItem = {
            'id': i+1,
            'title': getTitle,
            'image': getImage,
            'color': getColor,
            'size': getSize,
            'price': getPrice,
            'spanid': getSpan,
        };
        let data = JSON.parse(localStorage.getItem('newProduct'))
        if(localStorage.getItem('newProduct') == null) {
            oldItems.push(newItem);
            localStorage.setItem('newProduct', JSON.stringify(oldItems));
        } else {
            if(data.indexOf(newItem) == -1){
                oldItems.push(newItem);
                localStorage.setItem('newProduct', JSON.stringify(oldItems));
            }else{
                alert('element already added')
            }
        }
    })
} 

My problem is that I’ve tried to create a validation to check if the element has already been added to the local storage, so in that case there should appear the alert, but it’s not working at all and I’m still being able to add an element to my localstorage after I added it for the first time. I can’t get of how to resolve this, any ideas? 🙂

Advertisement

Answer

So thanks for the help I’ve received from @traktor, I was able to come up with a solution to this problem. I’ve added a data-prodid to each product and then pass it as ‘id’ to localstorage. Then I check if there’s any element in my array that contains the same ID i’m clicking into and if there’s any result, then an alert gets executed. Otherwise, the element gets saved.

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
    let button = addCartItemButtons[i]
    button.addEventListener('click', function(event){
        let buttonClicked = event.target
        let getProdId = buttonClicked.parentElement.parentElement.parentElement.getAttribute('data-prodid')
        let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
        let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
        let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
        let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
        let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
        let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
        let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
        let newItem = {
            'id': getProdId,
            'title': getTitle,
            'image': getImage,
            'color': getColor,
            'size': getSize,
            'price': getPrice,
            'spanid': getSpan,
        };
        
        if(localStorage.getItem('newProduct') == null) {
            oldItems.push(newItem);
            localStorage.setItem('newProduct', JSON.stringify(oldItems));
        } else {
            let data = JSON.parse(localStorage.getItem('newProduct'))
            let idCheck = data.filter(x => x.id === newItem.id).map(x => x.foo);
            let idCheckResults = idCheck.length
            if(idCheckResults > 0){
                alert('element already added')
            }else{
                oldItems.push(newItem);
                localStorage.setItem('newProduct', JSON.stringify(oldItems));
            }
        }
        let windowCartProducts = JSON.parse(window.localStorage.getItem("newProduct"));
        let productsInCart = document.getElementById('cartProducts')
        let productsAdded = 0
        for(let i = 0; i < windowCartProducts.length; i++){
            productsAdded = windowCartProducts.length
        }
        productsInCart.innerHTML = productsAdded + `<i class="fas fa-shopping-cart"></i>`
    })
} 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement