1

Hello I know there are many questions similar to this but nothing fits my problem.

I have a key value in my localstorage called 'productsInCart'. This key value contains a JSON object which looks like this:

{"11011001":{"id":11011001,"name":"42 Cable","price":4,"inCart":1},"11011002":{"id":11011002,"name":"22 Cable","price":4,"inCart":1}}

Now i want to delete/remove one value for example the value with the id '11011002'. How can I do that?

What I tried so far:

var items = JSON.parse(localStorage.getItem("productsInCart"));
for (var i = 0; i < items.length; i++) {
                               var items = JSON.parse(items[i]);
                               if (items.item_id == item_id) {
                                   items.splice(i, 1);
                               }
                           }
                           items = JSON.stringify(items);
                           localStorage.setItem("productsInCart", items);

I know this wont work because its not an array, but maybe someone has an idea on how to change it?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
  • 2
    Does this answer your question? [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – pilchard Nov 01 '20 at 12:12
  • 1
    `delete items['11011002']` – pilchard Nov 01 '20 at 12:14
  • @pilchard yes it works but it deletes the json object only temporarly when i try to put the object back in the localstorage with 'localStorage.setItem("productsInCart", items);' i get an error – letstrythisone44 Nov 01 '20 at 12:33
  • You need to stringily it first: `localStorage.setItem("productsInCart", JSON.stringify(items));` – pilchard Nov 01 '20 at 13:02

2 Answers2

1

So the suggestion by pilchard was right i just needed to delete the Object with

delete items[item_id];

and after that put it back in the localstorage with

items = JSON.stringify(items);
localStorage.setItem("productsInCart", items);

This worked fine for me, thanks

  • you should consider using functional approach whenever possible and make use of the available methods like filter in this case, anyhow +1 – EugenSunic Nov 01 '20 at 12:37
0

Once you pull it out from localStorage you need to transform it to an array and then filter it by your criteria:

Example:

const storage = {
  "11011001": {
    "id": 11011001,
    "name": "42 Cable",
    "price": 4,
    "inCart": 1
  },
  "11011002": {
    "id": 11011002,
    "name": "22 Cable",
    "price": 4,
    "inCart": 1
  }
};


const list = Object.keys(storage).map(key => ({
  [key]: storage[key]
}));
const filteredList = list.filter(item => Object.keys(item)[0] !== '11011002');
console.log(filteredList)

Setting the new structure into the localStorage use this: localStorage.setItem("productsInCart", JSON.stringify(filteredList))

EugenSunic
  • 13,162
  • 13
  • 64
  • 86