2

I am new to JavaScript programming and react. I have a data structure which I converted using the array.reduce method to the below given array.

My objective is to get the array re-structured in-order to use this is in a chart to visualize the data using react chart js 2.

const charData = [
    {
        "year": "2020",
        "value": [
            {
                "levelName": "Platinum",
                "yearlyCount": "1074"
            },
            {
                "levelName": "Gold",
                "yearlyCount": "1847"
            },
            {
                "levelName": "Silver",
                "yearlyCount": "4804"
            }
        ]
    }
]

i need the below structure

[
{
"year": "2020",
"Platinum": "1074",
"Gold": "1847",
"silver": "4804"
}
]

1 Answer 1

3

use map with reduce

const charData =  [
    {
        "year": "2020",
        "value": [
            {
                "levelName": "Platinum",
                "yearlyCount": "1074"
            },
            {
                "levelName": "Gold",
                "yearlyCount": "1847"
            },
            {
                "levelName": "Silver",
                "yearlyCount": "4804"
            }
        ]
    }
]

const res = charData.map(item => {
  const subRes = item.value.reduce((acc,i) => {
    return {
     ...acc,
     [i.levelName]  : i.yearlyCount
     
    }
  }, {})
  
  return {
    year: item.year,
    ...subRes,
  }
  
})

console.log(res)

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

Comments

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.