0

I have data like so:

    {
      "title": 0,
      "name": 0,
      "score": 0,
      "summary": [
        {
          "id": 1,
          "start": "2019-11-01",
          "end": "2019-11-04"
        },
        {
          "id": 2,
          "start": "2019-11-01",
          "end": "2019-11-04"
        }
      ]
    }

I am trying to access the first element of summary, so I have tried this:

    const newDate = new Date(data?.summary.map((d: any, index: number) => {
               if (index === 0) {
                 return (
                 new Date(d.start)
               )
          }
     })),

although it's working i get the warning:

Array.prototype.map() expects a value to be returned at the end of arrow function array-callback-return

I know it must be because I am not returning anything in the callback and the return is in the if statement?

3
  • 1
    Why using map in the first place instead of direct accesss to the array element? Commented Nov 4, 2021 at 11:58
  • 2
    Why not data?.summary[0]?.start Commented Nov 4, 2021 at 11:58
  • Over thinking the issue, thanks that did work Commented Nov 4, 2021 at 12:04

2 Answers 2

1
if (index === 0) {
                 return (
                 new Date(d.start)
               )

You are only returning a value if index === 0.

Im not sure what are you trying to achieve:

const newDate = new Date(data?.summary.map((d: any, index: number) => {
           if (index === 0) {
             return (
             new Date(d.start)
           )
      }
 })),

I suppose:

const newDate = newDate(data?.summary[0]?.start) 

Will do the thing.

Sign up to request clarification or add additional context in comments.

3 Comments

So what would be the workaround?
See my updated post. When you are dealing with a single value rather than with an array, you dont need map or any other method of array.
Over thinking the issue, thanks that did work
1

You can access to the first element without using map function:

const newDate = new Date(data?.summary[0].start)

1 Comment

Over thinking the issue, thanks that did work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.