更改 localStorage 对象中的特定值

Change the specific value in a localStorage Object

我有一段代码应该在 localStorage 中搜索 JSON 数组并修改特定“设备”中的 isTaken 值(例如我正在尝试使用250ml Flask 所以我输入设备名称“250ml flask”并将该烧瓶的 isTaken 值修改为 true)

JSON 格式如下:

equipmentdata = [
   {
      "id":1649778788049,
      "name":"500ml Flask",
      "type":"Flask",
      "isTaken":false,
      "dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
   },
   {
      "id":1649778800655,
      "name":"250ml Flask",
      "type":"Flask",
      "isTaken":false,
      "dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
   },
   {
      "id":1649778809178,
      "name":"Measuring Cylinder",
      "type":"mesCyl",
      "isTaken":false,
      "dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
   }
]

我的JS如下,

function takeHandler() {
        const date = new Date();
        let finalD = date.toUTCString();
        let teachName = document.getElementById("name").value;
        let equipmentName = document.getElementById("eqname").value;
        let output = teachName + " took " + equipmentName + " at " + finalD;

        localStorage.setItem("equipmentTaken", null);
        
        var eqhis = JSON.parse(localStorage.getItem("equipmentTaken")) || [];
        eqhis.push(output)
        localStorage.setItem("equipmentTaken", JSON.stringify(eqhis));
        
        let finalout = localStorage.getItem("equipmentTaken");

        document.getElementById("output").innerHTML = finalout;

        var currentData = localStorage.getItem("equipmentdata");
        currentData = currentData ? JSON.parse(currentData) : {};
        currentData[eqname, isTaken] = true;
}

主要错误是最后一行,我不太擅长 javascript,我无法真正从 JSON 中获取“eqname”值并替换其“isTaken”值true

我的预期输出是这样的

{
      "id":1649778800655,
      "name":"250ml Flask",
      "type":"Flask",
      "isTaken":true,
      "dateAdded":"Tue, 12 Apr 2022 15:53:00 GMT"
   },

语法无效。

// Invalid assignment, this doesn't work in javascript. We need the key as a string
currentData[eqname, isTaken] = true;

// Should be
currentData['eqname'] = true;
currentData['isTaken'] = true;

// As a oneliner, assign object directly. Here we don't need string flaps
currentData = { eqname: true, isTaken: true }

试试这个,它已经过测试并且工作正常

var currentData = localStorage.getItem("equipmentdata");
currentData = currentData ? JSON.parse(currentData) : {};

updateIsTaken(currentdata,"250ml Flask");

 localStorage.setItem("equipmentdata", currentdata);


function updateIsTaken(equipment, name)
{
  equipment.forEach(item => {
    if(item.name==name)
    {
      item.isTaken=true;
    }
  });
}

而且我不知道你如何将数据保存在本地存储中,所以也许你不需要解析。