skip to Main Content

I’m trying to update a localstorage item with a new updated array. The problem I’m facing is that I just can’t update my array properly and send it to the localstorage item. So what I’m trying is to get the localstaorage item first. Then look for an existing object with key qid. If that is found then update the qty value with qP_val. That I was able to get to work but how can I update the existing array stored_quote with an updated version of this array?

function updateQuoteProduct(qP, qP_val){

    var stored_quote = JSON.parse(localStorage.getItem("iwQuote")); 

    obj = stored_quote.findIndex((obj => obj.qid === qP));

    stored_quote[obj].qty = parseInt(qP_val)

    /* now I want to push the updated array back to */ 
    /* the original stored_quote array and replace  */ 
    /* the old object                               */
    /********************************************** */
    
    stored_quote.push(stored_quote[obj])
    

    /* update the localStorage again with new data */
    localStorage.setItem("iwQuote", JSON.stringify(stored_quote));
    

}

2

Answers


  1. I think that after you update the object, you push the array again and it creates a duplicate object.

    function updateQuoteProduct(qP, qP_val){
    var stored_quote = JSON.parse(localStorage.getItem("iwQuote")); 
    
    var objIndex = stored_quote.findIndex((obj => obj.qid === qP));
    
    stored_quote[objIndex].qty = parseInt(qP_val);
    
    
    localStorage.setItem("iwQuote", JSON.stringify(stored_quote));
    

    }

    Login or Signup to reply.
  2. This statement stored_quote.push(stored_quote[obj]) is causing the issue as you are pushing the updated object back into the array. Hence, it is duplicating it instead of overriding.

    Hence, You don’t need to push the object again. Instead, you can directly update the object in the array (which you already doing), and it will automatically reflect the changes.

    Example :

    function updateQuoteProduct(qP, qP_val) {
    
        var stored_quote = JSON.parse(localStorage.getItem("iwQuote")); 
    
        const index = stored_quote.findIndex((obj => obj.qid === qP));
    
        if (index !== -1) {
            stored_quote[index].qty = parseInt(qP_val)
            localStorage.setItem("iwQuote", JSON.stringify(stored_quote));
        }      
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search