Success Man Success Man - 1 year ago 96
JSON Question

How can I remove data by index array which is stored in local storage?

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

brk brk
Answer Source

You can use splice to remove an item from the array

// Clearing all localStorage value. No need to use below line in your code
// 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))


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download