在javascript中向数组或对象添加多个值

时间:2013-10-01 14:43:43

标签: javascript arrays object structure

我喜欢有数组或对象:

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

让自己:

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

此处是 javascript ,目前正在实施数组

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

请帮助获取结构化数组或对象

2 个答案:

答案 0 :(得分:8)

将包含数据的对象推送到数组中:

result.push({text: text, id: id});

答案 1 :(得分:0)

假设您要将所有答案存储到单个数组中,可以使用concat来获得预期结果并同时减少代码量:

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

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

以下是concat的工作原理(mdn doc):

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