Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON Array key dynamically in JavaScript [duplicate]

I'm Having a JSON that is getting creates in for-loop.

Here my main requirement is to create the Key from a predefined variable.

Here is the code that I'm using.

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

Looking into the other SO posts, I'm able to find on how can I replace intents variable, but here in my case, I want to replace intentName with name in the output.

Expected output is

{"intents":{"Hello":["Hello Trt","Ho there","I'm up"]}}

Please let me know on how can I achieve this.

Thanks

like image 402
user3872094 Avatar asked Mar 03 '23 21:03

user3872094


2 Answers

I think the below code satisfies your requirement.

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));
like image 141
Jins Thomas Shaji Avatar answered Mar 05 '23 11:03

Jins Thomas Shaji


You can do like this:

intents[name]= rows;
like image 39
Rajeev Avatar answered Mar 05 '23 09:03

Rajeev