Search code examples
javascriptreactjsapexcharts

Cannot get data formatted correctly for apexcharts


I receive data like this from an API

{
    "Bob Knight": 30774.72000002,
    "Samuel Herman": 10310.61000004,
    "Lucie Perry": 26308.41,
    "Andreas Smith": 8960.189999999999,
    "Frederic Smith": 2029.5000000599998,
}

I'm trying to display this in a bar chart using apex charts in my react app however I can't seem to format the data in the correct way to get apex to display anything. I have tried formatting in javascript like this:

{
    {x: "Bob Knight", y:"30774.720002"},
    ...
}

Which seems to be what the documentation suggest however it doesn't render anything. Below are the useful bits of my component

constructor(props) {
        super(props);
        this.state = {
            options: {
                chart: {
                    id: "basic-bar"
                },
                xaxis: {
                    type: 'category'
                }
            },
            values: []
        }
    }

    componentDidUpdate(prevProps) {
        if (!equal(this.props.selectedDate, prevProps.selectedDate))
        {
            var m = moment(this.props.selectedDate).format("M");
            var y = moment(this.props.selectedDate).format("YYYY");
            axios.get('http://localhost:8080/opportunity/owner/' + y + '/' + m)
                .then(res => {
                    values = res.data;
                    this.setState({
                        values
                    })
                })
                .catch(console.log)
        }
    }

render(
<Chart series = {this.state.values} type ='bar' options ={this.state.options}/>

Solution

  • const obj = {
      "Bob Knight": 30774.72000002,
      "Samuel Herman": 10310.61000004,
      "Lucie Perry": 26308.41,
      "Andreas Smith": 8960.189999999999,
      "Frederic Smith": 2029.5000000599998,
    }
    
    const arr = Object.entries(obj).map(x => ({
      'x': x[0],
      'y': x[1]
    }))
    console.log(arr)