首页 > 解决方案 > 使用路径访问 json 中的深度键并使用给定参数更新它

问题描述

我有一个嵌套的 json 对象,我有一个路径列表(模式在下面给出),我想根据路径动态更改一些值,其余对象保持不变。我们有样本数据:

export const newTemplate = {
  "patientInfo": {
    "name": ".document.author.name.given",
    "address": [
      {
        "country": "pakistan",
        "city": "rawalpindi",
        "disease": [
          {
            "id": 'HX-12',
            "name": "Flu"
          },
          {
            "id": 'HX-12',
            "name": "Fever"
          }
        ]
      }
    ],
    "phone": ".document.author.phone",
    "document": {
      "name": ".document.documentation_of[0].name"
    }
  },
  "location": ".document.location",
  "allergies": ".allergies",
  "commonInfo": {
    "common": {
      "allergies": ".allergies",
      
    }
  }
}

我们有一条路

const path = .patientInfo.address[0].disease[1].name

我想通过这条路径将“名称”Fever 更改为 Dhairiya

`${newTemplate}${path}` = "Dhairiya" 
// it will become like this.
// newTemplate.patientInfo.address[0].disease[1].name = "Dhairiya"

标签: jsonjavascript-objectsupdates

解决方案


推荐阅读