0

I'm trying to create a json object in javascript containing dynamic values. I need to pass this JSON Object to server through an AJAX call. But I'm unable to add the dynamic values.

var finalJSONObj={};
for loop(int i = 0; i<10;i++){
    // gets the values of rows i need to add .. 
    var taskValue = tasks[i]; // need to add this in the JSON Object
}

My final JSON object should look like:

finalJSONObj = {
    tasks1: 'taskValue',
    tasks2: 'taskValue',
    tasks3: 'taskValue',
    tasks4: 'taskValue',
    userId: 'abcd',
    date: '23/09/2016'
};

Need to add the "taskValue" retrieved from the for loop for each task in the JSON Object. Any Thoughts?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
skylark
  • 11
  • 1
  • 5
  • Do you know how to add `key`/`value` pair to a Javascript Object? Please refer [this](http://stackoverflow.com/a/1168814/427146) – sabithpocker Feb 21 '16 at 10:05

2 Answers2

1

How about:

var finalJSONObj={};
for (var i = 0; i<tasks.length; i++) {
    finalJSONObj[('tasks' + (i+1))] = tasks[i];
}
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
0

You are doing it wrong. In forloop just change this syntax

var finalJSONObj={};
  for loop(int i = 0; i<10;i++){
  // gets the values of rows i need to add .. 
  finalJSONObj['task'+ (i + 1)] = tasks[i]; // need to add this in the JSON Object
}

Here key will be task + i which will be task1, task2 etc and value will be mapped to this key from your tasks array.

Avinash Agrawal
  • 1,038
  • 1
  • 11
  • 17