skip to Main Content

This is the json data I am pulling from the backend API:

[
    {
        "year": 2024,
        "month": 7,
        "revenue": 27000
    },
    {
        "year": 2024,
        "month": 8,
        "revenue": 27000
    }
]

However in order to use nivo line charts to graph the data the data must be in the following format.


Array<{
    id:   string | number
    data: Array<{
        x: number | string | Date
        y: number | string | Date
    }>
}>

I can manipulate the data on the backend but I’m having a hard time figuring out whether it’s easier to manipulate the data via the frontend to arrange in this format.

2

Answers


  1. Chosen as BEST ANSWER

    I hacked away at decent way of getting the output that I need using kamran's code above as a starting point. However I think doing it on the backend is the best method moving forward.

    const data = [
        {
            "year": 2024,
            "month": 7,
            "revenue": 27000
        },
        {
            "year": 2024,
            "month": 8,
            "revenue": 27000
        },
        {
            "year": 2023,
            "month": 9,
            "revenue": 13000
        }
    ]
    
    const restructuredData = []
    
        data.forEach(item => {
            const {year: id, month: x, revenue: y} = item
            restructuredData.push({id, data: [{x, y}]})
        })
        
    const arrayHashmap = restructuredData.reduce((obj, item) => {
      obj[item.id] ? obj[item.id].data.push(...item.data) : (obj[item.id] = { ...item });
      return obj;
    }, {});
    
    const mergedArray = Object.values(arrayHashmap);
    

  2. i think you can do these:

    `

    const data = [
        {
            "year": 2024,
            "month": 7,
            "revenue": 27000
        },
        {
            "year": 2024,
            "month": 8,
            "revenue": 27000
        }
    ]
    
    const restructuredData = []
    
    data.forEach(item=>{
        const {year:id,month:x,revenue:y} = item
        restructuredData.push({id,data:[{x,y}]})
    })`
    

    and there is result:

        [
      {
        "id": 2024,
        "data": [
          {
            "x": 7,
            "y": 27000
          }
        ]
      },
      {
        "id": 2024,
        "data": [
          {
            "x": 8,
            "y": 27000
          }
        ]
      }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search