简体   繁体   中英

JavaScript : How do i push new column/row to the JavaScript Array during for..loop iteration?

i have my service response as below and i want to push a new row/column when i am iterating the array using for.. loop?

Service Response

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

How do i push my sessionDate to the data.message.student[i] object and it got pushed further into myArray?

You can use Array#map() for generating an array.

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

I hope this help

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

Regards.-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM