Search code examples
javascriptjsondomlawnchair

concatenation array of objects with javascript


I am taking questions from user and save them in DOM using Lawnchair.first step of declaration

var dbQuestions = new Lawnchair({name:'questions'}, function(obj) { consol('questions initialized'); }); 

User can input QuestionText,Choice,NextQuestionID and click save.Then each question is converted to below format

var survey= {   
"name": "Internet Based survey",
"sortOrder":10,
"questions" : [
    { "QuestionID": "1", "SurveyID":1, "QuestionText":"Excuse me Sir/Madame, do you have 60 seconds to answer a few questions today?", "SortOrder":"10", "Choices": [{ "ChoiceID":"1", "Choice":"Yes", "NextQuestionID":"3", "InitiateSurvey":"true" }, 
                      { "ChoiceID":"2", "Choice":"No", "NextQuestionID":"1" }, 
                      { "ChoiceID":"3", "Choice":"What is it About?", "NextQuestionID":"2" }] 
    }]};

and saves

dbQuestions.save({key:'Q',value:survey},function(obj) {
    consol('Question Saved successfully');

});

After saving first question user will enter next question. The above method works fine but i need to save in a different way. suppose user saves 3 questions and i want to store in below format so that i can access questions easily.

var survey = {  
"name": "Internet Based survey",
"sortOrder":10,
"questions" : [
    { "QuestionID": "1", "SurveyID":1, "QuestionText":"Excuse me Sir/Madame, do you have 60 seconds to answer a few questions today?", "SortOrder":"10", "Choices": [{ "ChoiceID":"1", "Choice":"Yes", "NextQuestionID":"3", "InitiateSurvey":"true" }, 
                      { "ChoiceID":"2", "Choice":"No", "NextQuestionID":"1" }, 
                      { "ChoiceID":"3", "Choice":"What is it About?", "NextQuestionID":"2" }] 
    }, 
    { "QuestionID": "2", "SurveyID":1, "QuestionText":"It is about a way to earn a little extra money with a side business", "SortOrder":"15", "Choices":[{ "ChoiceID":"1", "Choice":"Yes", "NextQuestionID":"3", "InitiateSurvey":"true" }, 
               { "ChoiceID":"2", "Choice":"No", "NextQuestionID":"1" }] 
    }, 
    { "QuestionID": "3", "SurveyID":1, "QuestionText":"Are you on the internet?", "SortOrder":"10", 
        "Choices":[{ "ChoiceID":"4", "Choice":"Yes", "NextQuestionID":"4" }, 
                   { "ChoiceID":"5", "Choice":"No", "NextQuestionID":"1" }] 
    }]};

So my question is how can i save questions where each question will save under question attribute.

Thanks in advance.


Solution

  • You can try this

    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