如何过滤含指定关键字的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
相关产品推荐
相关产品推荐

