【问题标题】:Store data with a dynamic key in a nested object using local storage使用本地存储将具有动态键的数据存储在嵌套对象中
【发布时间】:2019-10-24 01:43:10
【问题描述】:

以下对象存储在 localStorage 中以模拟服务器端登录/注销。我有逻辑可以找到当前用户。

let defaultUsers = [
  { email: "test@test.com", password: "test123", favs: [] },
  { email: "dummy@dummy.com", password: "dummy123", favs: [] },
  { email: "example@example.com", password: "example123", favs: [] }
];

这个想法是针对当前用户,我想在该特定用户的 favs 数组中存储最喜欢的图像 [有适当的逻辑来识别一堆图像中点击的图像]。我写了下面的逻辑,但它不起作用。

for (let usrs of Object.values(localStorage)) {
       JSON.parse(usrs).map(usr => {

       // imgURL is the url of image marked as favorite
       return usr.email === currentUsr ? localStorage.setItem(usr.favs, 
       imgURL)  : null;
      }
}

我非常感谢这里的任何帮助。

【问题讨论】:

  • 你如何在 localStorage 中存储defaultUsersObject.values(localStorage) 返回 localStorage 中所有值的数组,而不仅仅是用户。
  • 我像localStorage.setItem("defaultUsers", JSON.stringify(defaultUsers)) 一样存储它。是的,如果您注意到我使用了 map 方法,我了解 Object.values(localStorage) 返回 localStorage 中所有值的数组。

标签: javascript json reactjs local-storage


【解决方案1】:

Object.values(localStorage) 返回本地存储中所有值的数组。

由于本地存储 keysvaluesalways stored as strings,因此您将获得一个字符串数组。

在您的代码中,您正在对该数组进行迭代,然后使用JSON.parse() 将每个字符串转换为一个对象。结果对象是用户对象,例如{ email: "test@test.com", password: "test123", favs: [] },您不能在其上应用map() 方法 因为它不是数组。

您可以改为如下所示。

// Get users from localStorage.
let users = JSON.parse(localStorage.getItem("defaultUsers"));

// Update image URL.
let modifiedUsers = users.map(user => {
  // Not copying the reference to prevent mutating original array.
  let favs = [...user.favs]; 

  if (user.email === currentUsr) {
    favs.push(imgURL);
  }

  return {
    ...user,
    "favs": favs
  };
});

// Update users in localStorage.
localStorage.setItem("defaultUsers", JSON.stringify(modifiedUsers));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2020-11-05
    • 2011-08-21
    相关资源
    最近更新 更多