2017-08-28 127 views
-1

如果我CONSOLE.LOG(localStorage.getItem( 「cartCache」)),其結果是這樣的:如何通過存儲在本地存儲中的索引數組刪除數據?

{"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"} 

我想通過索引陣列

例如,當以去除在緩存中的數據我刪除索引數組= 0,得到的結果是這樣的:

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

又如,當我刪除索引陣列= 1,結果是這樣的:

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

我該怎麼做?

我嘗試這樣的:

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

這似乎是不正確的做法

+0

你到目前爲止試過了什麼?請在此處添加您的代碼 –

+2

可能的重複[如何從JavaScript中的數組中刪除特定元素?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element -from-an-array-in-javascript) –

+0

@Dinesh,這不重複。我的數組是不同的 –

回答

1

您可以使用splice從數組

// 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

4

localStorage.getItem("cartCache")回報你們兩個對象 - 數據高速緩存過期console.log您再次localStorage的

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

然後,你會看到已刪除的元素:如果你想刪除的元素n數據高速緩存,通過

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

刪除它,以適應它在你的代碼。

0

關鍵詞「刪除」刪除項目刪除deleteIndex只在retrieveObj它不更新您的localStorage的值。爲了更新localStorage的使用:

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