jStorage icon indicating copy to clipboard operation
jStorage copied to clipboard

Search for a string among keys

Open Paike opened this issue 11 years ago • 2 comments

If you need to search among the keys for a given string you could clone the index-function and modify it:

searchIndex: function(string){
            var index = [], i;
            for(i in _storage){
                if(_storage.hasOwnProperty(i) && i != "__jstorage_meta"){
                    if(i.indexOf(string) !== -1) index.push(i);
                }
            }
            return index;
        }

It will return an array with keys containing the string.

Paike avatar May 10 '13 21:05 Paike

Wish I'd seen that before I wrote this, handy if you'd prefer an array of items with a _key property.

/**
 * Access records matching a string.
 *
 * @param {string} string
 *   Text of the string to return values for. OPTIONAL.
 *
 * return {array}
 *   Array list of localStorage objects, keys added as "_key" property.
 */
$.jStorage.search = function search(string) {
  var results = $.jStorage.index(),
      returnVals = [];

  for (var i in results) {
    // Remove unwanted types and return records.
    if (string) {
      if (results[i].match(new RegExp(string, "g")) !== null) {
        returnVals.push($.extend(
          $.jStorage.get(results[i]), {_key: results[i]}
        ));
      }
    }
    else {
      // Return everything.
      returnVals.push($.extend(
        $.jStorage.get(results[i]), {_key: results[i]}
      ));
    }
  }

  return returnVals;
};

doublejosh avatar Aug 12 '15 05:08 doublejosh

Here's a possibility... https://github.com/andris9/jStorage/pull/96

doublejosh avatar Aug 12 '15 06:08 doublejosh