1

i like to have array or object like:

[0]
   text:"first"
   id: 1
[1]
   text:"second"
   id: 2
[2]
   text:"third"
   id: 3

getting myself:

1: first
2: 1
3: second
4: 2
5: third
6: 3

here is my javascript with implementation for the array at the moment:

 var numberOfQuestions = questionaireResult.numberOfQuestions;
                var i;
                var j;
                var result = [];

                for (i = 0; i < numberOfQuestions; i++) {
                    debugger;
                    var question = questionaireResult.questions[i].text;
                    var questionID = questionaireResult.questions[i].id;


                    for (j = 0; j < questionaireResult.questions[i].answers.length; j++) {

                        var text = questionaireResult.questions[i].answers[j].text;
                        var id = questionaireResult.questions[i].answers[j].id;
                        result.push(text, id);
                    }
}

please help to get a structured array or object

0

2 Answers 2

9

Push an object containing your data to the array instead:

result.push({text: text, id: id});
Sign up to request clarification or add additional context in comments.

1 Comment

@RagimsRagimovs: In the next version of JavaScript (ECMAScript6), it'll be even more concise: result.push({text, id}); (that will be functionally identical to the above; basically it just figures out the name of the property from the name of the variable). But we don't have ES6 yet. :-)
0

Assuming that you want to store all answers into a single array, you could use concat to get the expected result and reduce the amount of code at the same time :

var questions = questionaireResult.questions,
    result = [],
    l = questions.length,
    i = 0;

for (; i < l; i++) {
    result = result.concat(
        questions[i].answers
    );
}

Here is how concat works (mdn doc) :

var a = [1, 2, 3],
    b = [4, 5, 6];
a.concat(b); // [1, 2, 3, 4, 5, 6]

Comments

Your Answer

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.