JS Array map function, cannot read property of undefined

I have a complex JS array of objects and properties. Some of them return value but some return null, the problem is when I am mapping through the list it causes error whenever there is a null value.

I cannot filter out the array right now because I am already inside a loop and should not create another filtered array. What would my best approach be? I want my loop to return Array.Group.name[0].text and if it is not there just return null.

const x = [
      {
        "id": "1",
        "Groups": [
          {
            "name": [
              {
                "language": "en-US",
                "text": "REGULAR_TIME"
              }
            ],
            "isSystem": true
          },
          {
            "name": [
              {
                "language": "en-US",
                "text": "CHARGEABLE"
              }
            ],
            "isSystem": true
          }
        ]
      },
      {
        "id": "2",
        "Groups": [
          {
            "name": [
              {
                "language": "en-US",
                "text": "REGULAR_TIME"
              }
            ],
            "isSystem": true
          },
          {
            "name": [
              {
                "language": "en-US",
                "text": "CHARGEABLE"
              }
            ],
            "isSystem": true
          }
        ]
      }
      ]
      
      x.map(y=>y.Groups.name[0].text)
      
      console.log(x) 

Answer

Groups is an array too, so you have to use indexes to access its members like Groups[0]. It is not clear the name of what Groups element you want to get though.

Probably, you meant x.map(y=>y.Groups[0].name[0].text)

Groups being an array is an object too. so Groups.name gives you nothing since such a property isn’t present.

let x = [
      {
        "id": "1",
        "Groups": [
          {
            "isSystem": true
          },
          {
            "name": [
              {
                "language": "en-US",
                "text": "CHARGEABLE"
              }
            ],
            "isSystem": true
          }
        ]
      },
      {
        "id": "2",
        "Groups": [
          {
            "name": [
              {
                "language": "en-US",
                "text": "REGULAR_TIME"
              }
            ],
            "isSystem": true
          },
          {
            "name": [
              {
                "language": "en-US",
                "text": "CHARGEABLE"
              }
            ],
            "isSystem": true
          }
        ]
      }
      ];
      
      
      console.log(x.map(y => y.Groups[0].name?.[0].text));

      // or just filter the absent names out before the main routine.
      console.log(x.filter(y => y.Groups[0].name).map(y => y.Groups[0].name?.[0].text));