-1

If I console.log(localStorage.getItem("cartCache")), the result like this :

{"dataCache":[{"id":20,"quantity":1,"total":100000,"request_date":"27-08-2017 20:31:00"},{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}],"expired":"2017-08-28T03:55:21.521Z"}

I want to remove the data in the cache by index array

For example, When I remove index array = 0, the result to be like this :

{"dataCache":[{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}]}

Another example, When I remove index array = 1, the result to be like this :

{"dataCache":[{"id":20,"quantity":1,"total":100000,"request_date":"27-08-2017 20:31:00"}]}

How can I do it?

I try like this :

var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache")
delete retrievedObj['dataCache'][deleteIndex];

It seems that is not the right way

Syed Ayesha Bebe
  • 1,582
  • 1
  • 13
  • 25
Success Man
  • 5,513
  • 23
  • 109
  • 205

3 Answers3

4

localStorage.getItem("cartCache") returns you two objects - dataCache and expired. If you want to remove the element n of dataCache, remove it by

localStorage.getItem("cartCache").dataCache.splice(n,1);

To fit it in your code:

var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache");
retrievedObj.dataCache.splice(deleteIndex,1);

Then console.log your localStorage again and you'll see the element removed.

Aydin4ik
  • 1,447
  • 1
  • 8
  • 15
1

You can use splice to remove an item from the array

// Clearing all localStorage value. No need to use below line in your code
localStorage.clear();
// to be stored object
var x = {
  "dataCache": [{
    "id": 20,
    "quantity": 1,
    "total": 100000,
    "request_date": "27-08-2017 20:31:00"
  }, {
    "id": 53,
    "quantity": 1,
    "total": 200000,
    "request_date": "27-08-2017 20:38:00"
  }],
  "expired": "2017-08-28T03:55:21.521Z"
}
// Initially storing it in local storage using JSON.stringify
localStorage.setItem('storeData', JSON.stringify(x));
// Once stored retrieving the value using JSON.parse
var getItem = JSON.parse(localStorage.getItem('storeData'));
// setting the dataCache with new array. The new array will be created as splice is used. splice is used to remove an item from array,
//0 is the index of the array, while second parameter 1 is to represent how many item to be removed starting from 0 ndex
getItem.dataCache = getItem.dataCache.splice(0, 1);
console.log(getItem); // the modified object
// after operation setting it to local storage
localStorage.setItem('storeData', JSON.stringify(getItem))

DEMO

brk
  • 43,022
  • 4
  • 37
  • 61
0

Keyword "delete" deletes deleteIndex only in retrieveObj it doesn't update your localStorage value. In order to update localStorage use:

var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache")
delete retrievedObj['dataCache'][deleteIndex];
localStorage.setItem("cartCache", retrieveObj)
myxobek
  • 425
  • 4
  • 10