这个问题在这里已经有了答案:
Add a property to a JavaScript object using a variable as the name?
(14 个回答)
2年前关闭。
我有一个在 for-loop
中创建的 JSON .
这里我的主要要求是创建 Key
从预定义的变量。
这是我正在使用的代码。
var rows =["Hello Trt", "Ho there", "I'm up"];
var name="Hello";
var jsonData = {};
var intentName=[];
var mainPersonel = {};
var intents = {};
intents.intentName = rows;
mainPersonel.intents=intents;
console.log(JSON.stringify(mainPersonel));
查看其他 SO 帖子,我可以找到如何替换
intents
变量,但在我的情况下,我想替换 intentName
与 name
在输出中。预期输出为
{"intents":{"Hello":["Hello Trt","Ho there","I'm up"]}}
请让我知道如何实现这一目标。
谢谢
最佳答案
我认为下面的代码满足您的要求。
var rows =["Hello Trt", "Ho there", "I'm up"];
var name="Hello";
var jsonData = {};
var intentName=[];
var mainPersonel = {};
var intents = {};
intents[name]= rows;
mainPersonel.intents=intents;
console.log(JSON.stringify(mainPersonel));
关于javascript - 在 JavaScript 中动态创建 JSON 数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59878185/