Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify(localStorage) - filtering by key

I use a small code snipped to save the localStorage of my application as a string:

var saveStr = JSON.stringify(localStorage);

It works great at a first glance, but it basically dump the entire localStorage object, which I don't want. I'd like to stringify the localStorage, but only the keys that contains a certain string.

For instance: var saveStr = JSON.stringify(filteredLS("example"));

filteredLS should return the localStorage data, but only the keys that contains the string that was passed as an argument.

Someone knows an easy snipped to achieve this?

Thanks!

like image 845
Ricardo Avatar asked Apr 17 '26 06:04

Ricardo


2 Answers

Try this

function filteredLS(term) {
    var filteredObj = {};
    Object.keys(localStorage)

        .filter(function (key) {
            return key.indexOf(term) >= 0;
        })

        .map(function (key) {
            filteredObj[key] = localStorage.getItem(key);
        });

    return JSON.stringify(filteredObj);
}
like image 55
Samir Aleido Avatar answered Apr 19 '26 20:04

Samir Aleido


You should use the methods localStorage.getItem and localStorage.setItem. With those, you can write your own get & set functions to easily use JSON objects:

function get(item) {
    return JSON.parse(localStorage.getItem(item))
}

function set(item, value) {
    return localStorage.setItem(item, JSON.stringify(value))
}

// use like this:
set('foo', { bar: 1 })
var result = get('foo')
// result: { bar: 1 }
like image 23
Luca Steeb Avatar answered Apr 19 '26 18:04

Luca Steeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!