jmease
jmease

Reputation: 2535

Loop Through localStorage Containing Keyword

Is there a way to loop through localStorage in javascript or JQuery based on a keyword rather than looping through all of localStorage? I know I can do

 for (var i = 0; i < localStorage.length; i++)...

But I'd rather do something like

 $.each('localStorage:contains("keyword")')...

Upvotes: 2

Views: 1542

Answers (2)

pimvdb
pimvdb

Reputation: 154818

It's not directly possible to use DOM selectors for generic objects.

You could, however, create a little function that filters as per a passed function:

Object.filter = function(obj, func) {
    var res = {};

    for(var key in obj) {
        // filter out own properties (not length) that pass the filter function
        if(obj.hasOwnProperty(key) && key !== "length" && func(key, obj[key])) {
            res[key] = obj[key];
        }
    };

    return res;
};

Then you can do:

var filtered = Object.filter(localStorage, function(i, v) {
                                               // Simply speaking, '~' is the
                                               // same as checking for '!== -1'
                                               return ~i.indexOf("keyword");
                                           });
$.each(filtered, function(i, v) {
    // ...
});

Using this generic function you can build additional convenience functions like:

Object.keyContains = function(obj, contains) {
    return Object.filter(obj, function(i, v) {
        return ~i.indexOf(contains);
    });
};

Then to iterate localStorage the way you want is as easy as:

$.each(Object.keyContains(localStorage, "keyword"), function(i, v) {
    // ...
});

Upvotes: 2

Mike Neugebauer
Mike Neugebauer

Reputation: 33

JQuery has an inArray() method and I think that's what you're looking for -

JQuery inArray

In your case, you probably need something like this ...

var index = jQuery.inArray("keyword", localStorage);

// do what you need to with localStorage[index] from here

Upvotes: 0

Related Questions