'React, how to manipulate json in React after group by with reduce
I managed to get to a certain point with the original file by using the reduce() method, but I'm stuck with the last step. The object that gives me the array is called by "this.props.portfolio_treemap".
And this was the original array:
[
{
"id": 1,
"ticker": "VGHF11",
"total_today_brl": 10322.4,
"category": "Category 1",
},
{
"id": 2,
"ticker": "BTAL11",
"total_today_brl": 10942.25,
"category": "Category 1",
},
{
"id": 32,
"ticker": "BTC",
"total_today_brl": 2203.11,
"category": "Category 2",
},
]
I used this code with reduce to group by category:
class TreeMap extends React.Component {
constructor(props) {
super(props);
this.state = {
},
series: [
{
name: '',
data: []
}
]
}
}
render() {
return (
<>
{console.log(
this.props.portfolio_treemap.reduce(
(TreeMap, { category, ticker, total_today_brl }) => {
(TreeMap[category] = TreeMap[category] || []).push({ x: ticker, y: total_today_brl });
return TreeMap;
}, {})
)}
The output array from this is that one:
{
"Category 1": [
{
"x": "VGHF11",
"y": 10322.4
},
{
"x": "BTAL11",
"y": 10942.25
}
],
"Category 2": [
{
"x": "BTC",
"y": 2203.11
}
]
}
But actualy i would like to get this one:
[
{
"name": "Category 1",
"data": [
{
"x": "VGHF11",
"y": 10322.4
},
{
"x": "BTAL11",
"y": 10942.25
}
]
},
{
"name": "Category 2",
"data":
[
{
"x": "BTC",
"y": 2203.11
}
]
}
]
I don`t know how could i achive that, thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
