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"
}
]
CodePudding user response:
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)