首页 > 解决方案 > 在未知位置的特定键上更新 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确切的位置。

标签: javascriptjqueryjson

解决方案


您可以利用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)


推荐阅读