2014-02-13 3 views
2

비슷한 키를 가진 두 개의 json 객체가 question입니다. concate 두 개의 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 
}]}; 

나는 키 '질문'한 JSON 객체로를 concate하고 값이

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 
} 
]}; 

이하 나는 많은 방법을 시도하고 아래의 방법으로 가까운 나의 목적지에 배열처럼 될 것입니다 싶어하지만 배열을지지합니다 내가 question:Object 각 인덱스 객체를 포함 question:Array[2]을 concate 수있는 경우 데이터와 데이터 1 개체의

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

내 문제는 해결됩니다. 최종 출력은 question:Array[3]

어떤 도움을 주실 것입니다. 미리 감사드립니다.

+0

하지 JSON이 문제를 해결하려고 원하기 때문에. 또한 시도한 것과 실패한 것을 설명하십시오. –

+1

그냥 두 가지, 그리고 만약 당신이 '{질문': [질문, q2]}'var myObject = { 'question': [data.question, data1.question]}; ' – algrebe

답변

0

당신은 JQuery와

var final = $.merge(data, data1); 
0

음을 병합 할 수 있습니다, 여러분의 코드가 실제로 목록에 두 개체를 추진하고있다 그래서 u는 객체의 목록을 얻을. 귀하의 경우, 첫 번째 요소는 데이터이고 두 번째 요소는 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); 
+0

나는 10 질문을 사용자로부터 마침내 나는'question : Array [10]'처럼 각 배열 인덱스가 각 질문을 포함하고 싶다. 첫 번째 옵션은 두 개의 질문'question : Array [2]'를 입력 할 때까지 잘 작동합니다. 그러나 두 개 이상의 질문을 할 때 질문 [Array [2]'와 같이되어 Array [0]에 Array [2]와 Array [1]에 질문 3이 객체 형식으로 포함되어 있습니다. –

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 
관련 문제