4

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

user3872094
  • 3,269
  • 8
  • 33
  • 71
  • 2
    `intents[name]=rows` should do the trick, this produced the following output: `{"intents":{"Hello":["Hello Trt","Ho there","I'm up"]}}` – Stephen Byrne Jan 23 '20 at 12:12

2 Answers2

5

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

You can do like this:

intents[name]= rows;
Rajeev
  • 339
  • 4
  • 7