Sole
Sole

Reputation: 3340

React iterating over nested array gives error Cannot read properties of null (reading 'value')

I am getting an error, when trying to map over an nested array: The data structure is as follows:

Error: Cannot read properties of null (reading 'value')

export const testData = [
  {
    "date": [
      "2016-09-0912:00:00",
      "2015-09-0913:10:00"
    ],
    "title": [
      {
        "name": 'Name 1',
        "description": [
          {
            "value": 7898
          },
          {
            "value": 7898
          }
        ]
      },
      {
        "name": 'Name 2',
        "description": [
          {
            "value": 3244
          },
          {
            "value": 4343
          }
        ]
      },
      {
        "name": 'Name 3',
        "description": [
          null,
          null
        ]
      }
    ]
  }
]

I have tried:

 <div style={{ color: 'white' }}>
    Hello
    {testData.map(inner => {
      return (
        <p style={{color: 'white'}}>{inner.title.map(inside => {
          return (
          inside.description.map(point => {
            return (
              point.value
            )
          })
          )
        })}</p>
      )
    })}
  </div>

So a little confused ?

Upvotes: 0

Views: 288

Answers (1)

Moistbobo
Moistbobo

Reputation: 2962

This is because the value is null for the Name 3 object. A quick fix would be to use optional chaining.

ex

 <div style={{ color: 'white' }}>
    Hello
    {testData.map(inner => {
      return (
        <p style={{color: 'white'}}>{inner.title.map(inside => {
          return (
          inside.description.map(point => {
            return (
              point?.value // here
            )
          })
          )
        })}</p>
      )
    })}
  </div>

codesandbox

Upvotes: 1

Related Questions