Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS map array to return object of arrays for React

If I want to return an array of objects from a nested array in JS/React, what would be the way to do this? I have tried the following, but this gives an error about react children – objects cant be rendered as children try an array.

data:

{
      "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 have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const newArray = result?.summary?.map((inner: any) => {
    return (
        {
            from: new Date(inner?.start),
            to: new Date(inner?.end),
            label: {
                text: (inner?.id),
            },
         }
    )
})

I want to create a new array of objects with the data from the summary nested array?

any idea’s?

>Solution :

This is the issue. You need to convert your dates to strings. The third-party package you input this array tries to render the Date objects and fails to do so. The date is object type and that is what the error is all about.

Try this:

const newArray = result?.summary?.map((inner: any) => {
    return (
        {
            from: new Date(inner?.start).toString(),
            to: new Date(inner?.end).toString(),
            label: {
                text: (inner?.id),
            },
         }
    )
})

Use toDateString to get a formatted date string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading