如何从localStorage中删除对象或数组?

时间:2014-04-16 16:22:37

标签: javascript local-storage

我知道localStorage.removeItem(key)我可以按键删除项目。如果我的localStorage是单维的(即localStorage.search_near = 60654),那就没问题了。

但我有多级价值观。

我的localStorage.storedAddresses包含json对象:

[{
    "storeNumber": "010517",
    "zip": "20500",
    "state": "DC",
    "city": "WASHINGTON",
    "address": "1600 Pennsylvania Ave",
    "zone": null,
    "address_two": null,
    "name": "Second Choice",
    "type": "P",
    "dwellCode": "P",
    "key": 4,
    "defaultLocation": "N"
},
{
    "storeNumber": "714389",
    "zip": "60202",
    "state": "IL",
    "city": "EVANSTON",
    "address": "818 Brown Ave",
    "zone": null,
    "address_two": null,
    "name": "Test Storage",
    "type": "P",
    "dwellCode": "P",
    "key": 3,
    "defaultLocation": "N"
},
{
    "storeNumber": "316740",
    "zip": "70810",
    "state": "LA",
    "city": "BATON ROUGE",
    "address": "9884 BLUEBONNET BLVD",
    "zone": null,
    "address_two": null,
    "name": "Test2",
    "type": "P",
    "dwellCode": "P",
    "key": 2,
    "defaultLocation": "N"
}]

如何使用localStorage.removeItem()删除storeNumber为714389的对象?我是否必须loop through localStorage.storedAddresses并比较storeNumber值,然后在找到匹配时使用removeItem?或者有更直接的方式吗?

2 个答案:

答案 0 :(得分:2)

由于localstorage只能存储字符串,因此您必须使用JSON.parse解析该值并手动将其删除,然后重新插入。

var storedAddresses = JSON.parse(localStorage.storedAddresses); 
// storedAddresses is now an array of objects, not just a string

for ( var i = 0; i < storedAddresses.length; i++ ) {
    if ( storedAddresses[i].storeNumber === '714389' ) {
        // remove the object with storeNumber '714389' from the array
        storedAddresses.splice(i,1); 
    }
}

// insert the new stringified array into LocalStorage
localStorage.storedAddresses = JSON.stringify(storedAddresses);

答案 1 :(得分:0)

如果您使用的是jQuery,则可能需要使用用于搜索数组的grep。 有关更多信息,请参阅此处:

Find object by id in an array of JavaScript objects

您还可以使用这些库来查询JSON结构:

http://orangevolt.blogspot.com/2012/12/8-ways-to-query-json-structures.html