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.1m377 gold badges3.7k silver badges3.6k bronze badges
asked Feb 21, 2016 at 9:46
1
  • Do you know how to add key/value pair to a Javascript Object? Please refer this Commented Feb 21, 2016 at 10:05

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Works great! :)
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.

answered Feb 21, 2016 at 10:06

3 Comments

This works fine! :) I finally got the results iterating through the request.getParameterValues() in my servlet. Thanks a ton! :)
Always happy to help :) yw
This is not going to work, since 'task' + i + 1 will evaluate to task01, task11, etc. (It is grouped as ('task' + i) + 1).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.