javascript - 在未知位置的特定键上更新 JSON
问题描述
假设我有以下 JSON 字符串
var storage = {
"gear": {
"gear-type-small": {
"type": "gear",
"visible": false,
"gear-type-small-1": {
"type": "armor",
"price": 50,
"unlocked": true,
"bought": false
},
"gear-type-small-2": {
"type": "weapon",
"price": 100,
"unlocked": true,
"bought": false
}
}
}
}
我想读取并写入数据。为此,我需要知道每个节点的位置。例如。
storage['gear']['gear-type-small']['visible'] = true;
但是像这样选择正确的节点对我来说似乎有点奇怪。如果我知道一个节点是独一无二gear-type-small-2
的,gear-type-small
是否有可能在不知道完整路径的情况下直接操作该节点?
unlocked
在此示例中, “查找gear-type-small-2
并将其设置为true
”,但不知道gear-type-small-2
确切的位置。
解决方案
您可以利用JSON.stringify的替换函数来更新值,然后将 JSON 字符串解析回对象。
var storage = {
"gear": {
"gear-type-small": {
"type": "gear",
"visible": false,
"gear-type-small-1": {
"type": "armor",
"price": 50,
"unlocked": false,
"bought": false
},
"gear-type-small-2": {
"type": "weapon",
"price": 100,
"unlocked": false,
"bought": false
}
}
}
}
var result = JSON.parse(JSON.stringify(storage, function (key, value) {
if (key === 'gear-type-small-2') {
value.unlocked = true
}
return value
}));
console.log(result)
推荐阅读
- html - 如何在烧瓶中创建框架并将模板渲染成框架
- javascript - 在道具对象之外传递“道具”是一种反模式吗?
- tcl - 用于从目录中的文件中提取元素并制作列表的 TCL 脚本
- javascript - 傅里叶级数模拟器
- java - 使用 bootRun generate 运行时 Gradle 找不到符号 isEmpty
- angular - Ionic 4:iOS 设备无法识别 ngIf 中的值 0
- postgresql - Dockerized pgAdmin4:解释功能不起作用/表在 UI 中不可见
- javascript - 以组件为数据的材料表未在 onChange 事件中传递组件上下文
- c - 有人可以向我解释这段代码的逻辑吗?
- c# - 在单击提交按钮时保持我的进度条运行并冻结屏幕和后台代码应该运行