javascript - 如何将方法的参数传递到赋值运算符的左侧?
问题描述
我正在尝试更新量角器 nodejs 中 JSON 文件的键值对。无法将“键”参数传递到“等于”运算符的左侧以更新 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')
})
}
测试数据.json:
{
"LANG": {
"TEST1": {
"Default": {
"username": "value1",
"password": "value2"
}
},
"TEST2": {
"Default": {
"username": "value1",
"password": "value2",
"title": "test-name-05252020-4786"
}
}
}
它在第 5 行失败
我希望将密钥读作“标题”并将其赋值为“test-name-07282020-1234”。请在此处提供帮助!
解决方案
您必须使用括号符号访问,它完全符合您的用例:
data.LANG.TEST2.Default[key] = value;
推荐阅读
- android - 如何解决错误 org.json.jsonexception.No value fo login
- vb.net - sql中的更新语句不起作用,微软使用vb.net访问
- spss - 将字符串变量转换为 0-1 列
- woocommerce - WooCommerce - 在订单电子邮件中添加新的小计和重新排序字段
- python - 如何解决 python openssl load_cert_chain 函数错误?
- angular - Ionic Angular 不上传网页版文件
- ruby - 如何根据数组处理结果为变量赋值
- r - 如何将列表分成两部分,键和值?
- sql - 左连接空值
- python - ipPython 输入错误,它以 \x1b[4;710;528t. 颜色有问题吗?