使用JavaScript动态创建JSON数组键

4

我有一个在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"]}}

请告诉我如何实现这一目标。

谢谢


2
intents[name]=rows should do the trick, this produced the following output: {"intents":{"Hello":["Hello Trt","Ho there","I'm up"]}} - Stephen Byrne
2个回答

5
我认为下面的代码符合你的要求。

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));


3
你可以这样做:
intents[name]= rows;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接