首页 > 解决方案 > 更新 json 文件中的值

问题描述

json单击按钮时是否可以更新文件内的值?例如是这样的:

{
    "caught": "0",
    "id": 1,
    "location": "River",
    "north": "Nov ~ Mar",
    "price": 900,
    "south": "May ~ Sept",
    "tod": "All day"
},
{
    "caught": "0",
    "id": 2,
    "location": "Sea",
    "north": "Nov ~ Mar",
    "price": "2,500",
    "south": "May ~ Sept",
    "tod": "4pm - 9am"
}

我想将 id 为 1 的捕获从 0 更改为 1。这可能吗?顺便说一句,我正在使用javascript。

标签: javascriptjqueryjsonobjectupdates

解决方案


是的,这是可能的。

  1. 首先,确保您的按钮有一个 ID,如下所示:<button id="myButton"/>
  2. 为“click”事件附加一个事件监听器:
const element = document.getElementById('myButton');
button.addEventListener('click', (event) => modifyObject());
  1. 然后你可以编写你的“modifyObject”函数。这将映射您的元素数组,如果给定的项目具有特定的 ID,它将返回不同的结果。它应该如下所示:
arr.map(x => {
    if (x.id === 1) {
         return {
             ...x,
             caught: 1
         };
    }
    return x;
});

我正在使用有效扩展可迭代对象的扩展运算符 (...)。


推荐阅读