将动态键值添加到JSON对象

时间:2016-02-21 09:46:22

标签: javascript json

我正在尝试在包含动态值的javascript中创建一个json对象。我需要通过AJAX调用将此JSON对象传递给服务器。但是我无法添加动态值。

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
}

我的最终JSON对象应如下所示:

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

需要为JSON对象中的每个任务添加从for循环中检索到的“taskValue”。有什么想法?

2 个答案:

答案 0 :(得分:1)

怎么样:

var finalJSONObj={};
for (var i = 0; i<tasks.length; i++) {
    finalJSONObj[('tasks' + (i+1))] = tasks[i];
}

答案 1 :(得分:0)

你做错了。 在forloop中只需更改此语法

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
}

这里的key是task + i,它将是task1,task2等,value将从你的任务数组映射到这个键。

相关问题