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.1m377 gold badges3.7k silver badges3.6k bronze badges
2 Answers 2
How about:
var finalJSONObj={};
for (var i = 0; i<tasks.length; i++) {
finalJSONObj[('tasks' + (i+1))] = tasks[i];
}
answered Feb 21, 2016 at 10:07
Yaron Schwimmer
5,3675 gold badges40 silver badges60 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
skylark
Thanks! Works great! :)
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.
answered Feb 21, 2016 at 10:06
Avinash Agrawal
1,1481 gold badge12 silver badges17 bronze badges
3 Comments
skylark
This works fine! :) I finally got the results iterating through the request.getParameterValues() in my servlet. Thanks a ton! :)
Avinash Agrawal
Always happy to help :) yw
lang-js
key/valuepair to a Javascript Object? Please refer this