JavaScript:如何在for..loop迭代期间将新列/行推送到JavaScript数组?

时间:2016-03-22 22:25:26

标签: javascript arrays angularjs

我的服务响应如下所示,当我使用for ..循环迭代数组时,我想推送一个新的行/列?

服务响应

"message":
{
   "student" [

     {
       "name" : "student1", 
       "oDate" : "03/03/2016",
       "oTime" :  "5:00 PM"
     },
     {
       "name" : "student2", 
       "oDate" : "03/03/2016",
       "oTime" :  "6:00 PM"
},{
       "name" : "student3", 
       "oDate" : "03/03/2016",
       "oTime" :  "7:00 PM"
} ]        
     }

}     

var myArray =[];

for(var i=0; i<data.message.student.length; i++)
{
var sessionDate = a.oDate + a.oTime;
myArray.push(data.message.student[i]);
}

如何将 sessionDate 推送到data.message.student [i]对象并进一步推送到myArray?

2 个答案:

答案 0 :(得分:1)

您可以使用Array#map()生成数组。

&#13;
&#13;
var data = { message: { "student": [{ "name": "student1", "oDate": "03/03/2016", "oTime": "5:00 PM" }, { "name": "student2", "oDate": "03/03/2016", "oTime": "6:00 PM" }, { "name": "student3", "oDate": "03/03/2016", "oTime": "7:00 PM" }] } },
    myArray = data.message.student.map(function (a) {
        a.sessionDate = a.oDate + ' ' + a.oTime;
        return a;
    });

document.write('<pre>' + JSON.stringify(myArray, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我希望这个帮助

var myArray = [];

for(var i=0; i < data.message.student.length; i++) {
    data.message.student[i].sessionDate = a.oDate + a.oTime;
    myArray.push(data.message.student[i]);
}

问候.-