Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Get all keys matching a char string
Message
From
01/12/2015 04:48:04
 
General information
Forum:
HTML5
Category:
Local storage
Miscellaneous
Thread ID:
01628117
Message ID:
01628131
Views:
37
>Hi,
>
>Say I have the following strings (serialized JSON) (Key and Value in the local storage (simplified):
>
>
>"PM_ABCD","long string is here"
>"PM_1233", "another long string here"
>"ABC", "Another long string"
>"PM_G134555","long string"
>
>
>Can I get all keys - into an object - (without getting the Value) that start with a string "PM_"?

As Rob says you will need to iterate localStorage:
String.prototype.startsWith = function(startText) {
        return this.slice(0, startText.length) == startText;
    };
    
    var pmKeys = new Array();
    for (var x = 1; x < localStorage.length; x++) {
        var s = localStorage.key(x);
        if (s.startsWith("PM_")) {
            pmKeys.push(s);
        }
    }
But it may be better to store all those items as an array of objects under one key.e.g:
var toStore = [
    { Key: "PM_ABCD", Value: "long string is here" },
    { Key: "PM_1233", Value: "another long string here" },
    { Key: "ABC", Value: "Another long string here" },
    { Key: "PM_G134555", Value: "long string" }
];
localStorage.setItem("MyList", JSON.stringify(toStore));
Then you can pull them back into an array which is easier to manipulate:
var myList = JSON.parse(localStorage.getItem("MyList"));
var pmKeys = new Array();
    myList.forEach(function(item) {
        if (item.Key.slice(0, 3) == "PM_") {
            pmKeys.push(item.Key);
        }
    });
I usually pull any stuff that I'm likely to need from localStorage into memory when the page loads.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform