5

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}/>
Will Rollason
  • 125
  • 1
  • 1
  • 10

2 Answers2

1

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)
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
  • Can someone please help? https://stackoverflow.com/questions/62590738/how-to-remove-the-horizontal-lines-of-chart-its-axis-lines-in-angular – reacg garav Jun 26 '20 at 10:36
0

Checkout this codesandbox, I implemented a simple bar chart, data is y-axis values and categories in xaxis is x-axis labels. So from the object you can separate both of them like this

const obj = {
 "Bob Knight": 30774.72000002,
 "Samuel Herman": 10310.61000004,
 "Lucie Perry": 26308.41,
 "Andreas Smith": 8960.189999999999,
 "Frederic Smith": 2029.5000000599998
};
let categories = Object.keys(obj);
let data = Object.keys(obj).map(k => obj[k]);

after doing this set the categories and data in the state like this

this.setState({
  values: [...this.state.series, { data }],
  options: { ...this.state.options, xaxis: { categories } }
});

you have to add categories to xaxis in options object and data to values array

Hemanath
  • 1,075
  • 6
  • 15