首页 > 解决方案 > 如何按键对localStorage进行排序

问题描述

出于某种原因,localStorage 不会按照您向其中添加数据的顺序进行排序。

我已将 JS 日期毫秒存储为 localStorage 中的键。
如何从按 asc 键排序的 localStorage 中输出键和值?

我是否需要从 localStorage 创建另一个 VAR,然后对 VAR 进行排序?

标签: javascriptsorting

解决方案


如何使用 JSON.stringify(yourObject) 将时间保存为单个对象

就像是

const jsTimes = localStorage.getItem("times");
const times = jsTimes ? JSON.parse(jsTimes) : {};
...
times[new Date().getTime()] = "Now is the time";
localStorage.setItem("times",JSON.stringify(times));

或者,如果您必须

const times = Object.keys(localStorage)
  .filter(key => key.length === 13 && !isNaN(new Date(key))
  .map(key => key)
  .sort() // alphabetic sort is ok on a timestamp
  .map(key => ({[key]: localStorage[key] }));

推荐阅读