concat两个相同键的json对象

时间:2014-02-13 06:31:55

标签: arrays json object

我有两个类似键question的json对象。

var data = {"question":[{
    QuestionID : counter1,
QuestionText: question1, 
    Choices:[{ChoiceID:100,Choice:"Yes",NextQuestionID:counter},
             {ChoiceID:101,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}]};


var data1 = {"question":[{
    QuestionID : counter2,
QuestionText: question2, 
    Choices:[{ChoiceID:103,Choice:"Yes",NextQuestionID:counter},
             {ChoiceID:105,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}]};

我想将它们连接成一个带有键'question'的json对象,value将是如下所示的数组

var final = {"question":[
{
    QuestionID : counter1,
QuestionText: question1, 
    Choices:[{ChoiceID:100,Choice:"Yes",NextQuestionID:counter},
             {ChoiceID:101,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
},
{
QuestionID : counter2,
QuestionText: question2, 
    Choices:[{ChoiceID:103,Choice:"Yes",NextQuestionID:counter},
             {ChoiceID:105,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}
]};

我尝试了很多方法并且靠近我的目的地,但它创建了数据和data1对象

var jsons = new Array();
jsons.push(data);
jsons.push(data1);

如果我可以在每个索引包含对象的question:Objectquestion:Array[2]之间进行连接,我的问题就会解决。最终输出为question:Array[3]

任何帮助都将受到高度赞赏。 提前谢谢。

3 个答案:

答案 0 :(得分:2)

我通过

解决了这个问题
var index = 0; // number of question
$.each(previousData.question,function(){
           finalArray[index] = previousData.question[index]; //contain array
           index++; //here index is number of question
 });

 finalArray[index] = data.question;
 data = {'question': finalArray }; // convert array to object

答案 1 :(得分:0)

您可以通过jquery

进行合并
var final = $.merge(data, data1);

答案 2 :(得分:0)

好吧,你的代码实际上是将两个对象推送到一个列表中,所以你得到一个对象列表。在您的情况下,第一个元素是数据,第二个元素是data1。所以你实际上并没有得到所需的结果。

因为你想要一个对象试试这个

/* assuming data and data1 are created and both have the key question */
var final = {'question': [data.question, data1.question] };

// or using the concat feature
var final = data.question.concat(data1.question);