JSON.stringify(localStorage) - 按键过滤

时间:2018-02-14 21:29:20

标签: javascript arrays local-storage filtering

我使用一个小代码剪切来将我的应用程序的localStorage保存为字符串:

var saveStr = JSON.stringify(localStorage);

乍一看它效果很好,但它基本上会转储整个localStorage对象,这是我不想要的。我想将localStorage字符串化,但只包含包含某个字符串的键。

例如: var saveStr = JSON.stringify(filteredLS("example"));

filteredLS 应该返回localStorage数据,但只返回包含作为参数传递的字符串的键。

有人知道这很容易实现吗?

谢谢!

3 个答案:

答案 0 :(得分:4)

试试这个

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);
}

答案 1 :(得分:1)

您应该使用localStorage.getItem和localStorage.setItem方法。有了这些,你可以写自己的get&设置函数以轻松使用JSON对象:

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 }

答案 2 :(得分:1)

根据您的目标浏览器,您可能需要对此进行转换,但为了简洁起见,我采用(主要)es6风格 - 这应该在现代浏览器中运行

按键过滤对象:

const filterByKeys = obj => keys => Object.entries(obj)
  // keep only the keys we care about
  .filter( ([key, val]) => keys.includes(key) )
  // make a new object with just the filtered keys
  .reduce( (accum, [key, val]) => Object.assign(accum, {[key]:val} ), {} )

用法:

// create a function for getting select keys
const localStore = filterByKeys(localStorage)

// call that function with a list of keys you want
const myValues = localStore(['foo', 'bar'])

// and JSON for completeness

const localStoreJson = keys => JSON.stringify(localStore(keys))

备用选项,如果您将来正在进行转换或阅读 - 使用扩展运算符和压缩过滤器+简化为一步 - 为了您的目的,这可能是不必要的:

const filterByKeys = obj => keys => Object.entries(obj)
  // filter and reduce in one step
  .reduce( (accum, [key, val]) => keys.includes(key) ? {...accum, [key]:val } : accum, {} )