2017-08-28 5 views
-1

私は(localStorage.getItem( "cartCache"))、このような結果にconsole.log場合:ローカルストレージに格納されているインデックス配列でデータを削除するにはどうすればよいですか?

{"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 = 1、インデックスアレイを削除すると、結果はこのようになり、

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

別の例:

Iは索引配列= 0を削除した結果は次のようであると

どうすればいいですか?

私はこのようにしてみてください:

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

それはあなた二つのオブジェクト

+0

これまでに試したことはありますか?ここにコードを追加してください –

+2

[JavaScriptの配列から特定の要素を削除するにはどうすればいいですか?](https://stackoverflow.com/questions/5767325/how-do-remove-a-particular-element) -from-an-array-in-javascript) –

+0

@Dinesh、これは重複していません。私の配列は異なる –

答えて

1

あなたは

// 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")戻って正しい方法ではないようだ - データキャッシュ期限切れ。あなたはデータキャッシュの要素nを削除したい場合は、あなたのコードでそれを適合させるために

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

して削除:

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

その後、再びconsole.logあなたのlocalStorageとあなたは要素が取り除か表示されます。

0

キーワードは「削除」の配列から項目を削除するにはspliceを使用することができ、それはあなたのlocalStorage値を更新していないだけretrieveObjでdeleteIndexを削除します。 localStorageを更新するには:

var deleteIndex = 1; 
var retrievedObj = localStorage.getItem("cartCache") 
delete retrievedObj['dataCache'][deleteIndex]; 
localStorage.setItem("cartCache", retrieveObj) 
関連する問題