如何将方法的参数传递给赋值运算符的左侧?

How to pass parameter of a method to the left hand side of assignment operator?

我正在尝试更新量角器中 JSON 文件的键值对 nodejs.Am 无法将 'key' 参数传递到 [=26] 的左侧=] 运算符以更新 JSON 文件中的值。请找到以下代码并帮助我解决此问题:

调用方法:

this.test = async function () {
await writeToJSON(title, test-name-07282020-1234);
}

方法:

async function writeToJSON(key, value) {

  const { readFile, writeFile } = require('fs').promises;
  const jsonFilePath = `${__dirname}/testdata.json`;
  let data = JSON.parse(await readFile(jsonFilePath));

  data.LANG.TEST2.Default.key = value;  // line 5 ..due to key is not read from
  // the parameter passed in the method. It is trying to look the field 'key' in 
  //json file to update the value.

  writeFile(jsonFilePath, JSON.stringify(data, 2, 2)).then(() => {
    console.log('Finished writing to json file')
  })
}

testdata.json:

    {
  "LANG": {
    "TEST1": {
      "Default": {
        "username": "value1",
          "password": "value2"
      }
    },
    "TEST2": {
      "Default": {
        "username": "value1",
          "password": "value2",
            "title": "test-name-05252020-4786"

      }
    }

  }

它在第 5 行失败

我希望密钥读作 'title' 并为其分配值 'test-name-07282020-1234'。请帮忙!

您必须使用 brackets notation 进行访问,它非常适合您的用例:

data.LANG.TEST2.Default[key] = value;