1

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

}]
  • you don't have a "First Name" in the "fields" object. Also, "records" is an array of one object, you should access the first object in the array, and then get the fields property, like this: i["records"][0].fields. I would use typescript for this, you could define an interface and everything would be much easier. – Ninca Tirtil Mar 30 '22 at 09:45
  • Hi, that code was actually just an excerpt, i have modified the question after you posted your comment, thanks for pointing it out :) – Antony Rappai Mar 30 '22 at 09:51

2 Answers2

0

You must use "return" if you use "{}" brackets in your arrow function. Add "return newAtStudentObj;" at the end:

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

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

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.

Lazar Nikolic
  • 4,261
  • 1
  • 22
  • 46