javascript - 更新 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。
解决方案
是的,这是可能的。
- 首先,确保您的按钮有一个 ID,如下所示:
<button id="myButton"
/> - 为“click”事件附加一个事件监听器:
const element = document.getElementById('myButton');
button.addEventListener('click', (event) => modifyObject());
- 然后你可以编写你的“modifyObject”函数。这将映射您的元素数组,如果给定的项目具有特定的 ID,它将返回不同的结果。它应该如下所示:
arr.map(x => {
if (x.id === 1) {
return {
...x,
caught: 1
};
}
return x;
});
我正在使用有效扩展可迭代对象的扩展运算符 (...)。
推荐阅读
- json - 为字符串类型的 JSON 属性声明模式 ^(.*)$ 是否有价值/目的?
- python - 如何根据模式中的每个字段名称在python中索引数据?
- python - web2py - 从行对象中提取值并存储在变量中
- r - 如何将刻度标记添加到 RasterImage Plot?
- c# - 带有任务的 Xamarin 表单切换
- onclick - 动态 TImage 的 OnClick 事件
- go - 如何通过调用结构方法来启动/停止功能
- javascript - 将 Javascript 字符串转换为名称/值对对象
- ios - 安装react-native-custom-segmented控件,react-native项目需要安装ios框架
- python - 绘制非线性决策边界