javascriptarraysgoogle-apps-scriptjavascript-objectsairtable

Retrieve data from an array of objects in Google Script


i am trying to extract certain elements from the below array of objects called atstudentsarray and create a new array with objects. I have used the below map function but i can not get it to work.

var newAtStudentArray = atstudentsarray.map(i => {
    const newAtStudentObj = {}

    newAtStudentObj.last_name = i['records'].fields['Last Name']
   
  })

Below is an array called atstudentsarray

[{
    "records": [
        {
            "id": "rec02fiiNA",
            "createdTime": "2020-04-21T05:06:07.000Z",
            "fields": {
                "Last Name": "Lat",
                "Gender": "Male",
                "E-mail Address": "alath@bbc.lk",
                "Grade": "DP 2",
                "parent_id_2": [
                    "rec3TCndXH"
                 ]
         }

         {
            "id": "rec02fiiNA",
            "createdTime": "2020-04-21T05:06:07.000Z",
            "fields": {
                "Last Name": "Lat",
                "Gender": "Male",
                "E-mail Address": "alath@bbc.lk",
                "Grade": "DP 2",
                "parent_id_2": [
                    "rec3TCndXH"
                 ]
         }
             ]

}]

Solution

  • Your can try it like this:

    var newAtStudentArray = atstudentsarray[0].records.map(i => ({
        last_name: i.fields['Last Name']
      }))
    

    The reason why it didn't work for you is because atstudentsarray is not the array you should be doing map on but on records array.