Retrieve all data from LocalStorage (without knowing the key name)

泪湿孤枕 提交于 2019-12-20 12:39:29

问题


I'm looking for a way to get all the information out of localStorage. The trouble I'm having is I don't know what the data will be as it is user generated.

So here what happens, a user inputs some text, it uses javascript to manipulate it depending on what check boxes they have ticked on the input form. these boxes are for symbols for example if they tick the box for @ then the text + the @At (symbol then word) will be placed in local storage with the other half of the pair as a Boolean (1 or 0 in this case) representing whether its been checked.

the exact pair would look like this:

someString..@At        | 1
someString..#Hash     | 0

etc.

It should also be noted that this is intended to be used in a Chrome Extension so compatibility in other browsers is not a requirement for me (although it could well be usful to others reading this as I can't find anything else covering it on the web).

So, if there anyway I can extract all the values in localStorage without actually knowing the name of each key? Is it possible to use any kind of wild card or regular expression maybe, I have tried this but should make it work using a for loop.

Thanks, Wez


回答1:


window.localStorage.key is the solution. Example:

var i = 0,
    oJson = {},
    sKey;
for (; sKey = window.localStorage.key(i); i++) {
    oJson[sKey] = window.localStorage.getItem(sKey);
}
console.log(oJson);


来源:https://stackoverflow.com/questions/9144982/retrieve-all-data-from-localstorage-without-knowing-the-key-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!