You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤含指定关键字的localStorage键值对后执行JSON.stringify?

实现过滤特定键的localStorage筛选函数

没问题,我来帮你搞定这个需求!下面就给你实现符合要求的filteredLS函数,让你只导出键包含指定字符串的localStorage数据。

核心思路

我们需要遍历localStorage的所有键,筛选出包含目标字符串的键值对,把它们整理成一个新对象返回,这样JSON.stringify就能只处理这些符合条件的数据了。

完整实现代码

function filteredLS(targetStr) {
  const filteredData = {};
  
  // 遍历localStorage的所有键
  for (let i = 0; i < localStorage.length; i++) {
    const currentKey = localStorage.key(i);
    
    // 检查当前键是否包含目标字符串(区分大小写)
    if (currentKey.includes(targetStr)) {
      filteredData[currentKey] = localStorage.getItem(currentKey);
    }
  }
  
  return filteredData;
}

代码细节说明

  • 先创建空对象filteredData,用来存放筛选后的键值对
  • 通过localStorage.length获取总键数,循环遍历每一个键
  • 用localStorage.key(i)拿到当前循环对应的键
  • 如果需要不区分大小写的匹配,可以把判断条件改成这样:
    if (currentKey.toLowerCase().includes(targetStr.toLowerCase())) {
      // ...
    }
    
  • 符合条件的键值对会被存入filteredData,最后返回这个对象供JSON.stringify处理

使用示例

假设你的localStorage里有profile-example、app-settings、example-preferences这些键,调用filteredLS("example")后,返回的对象会包含profile-example和example-preferences的键值对,再执行JSON.stringify(filteredLS("example"))就能得到你需要的目标字符串啦!

内容的提问来源于stack exchange,提问作者Ricardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:12:09