skip to Main Content

I try to use the Highcharts JS library with Angular.
I use the Column Drilldown model.

GOAL :

The data part of the graph must look like this :

data: [{
  name: 'text name',
  y: 5,
  drilldown: 'text name'
}]

My goal is to fill that data part with an array instead of manually typing .

DATA :

My array looks like this :

var arr = { "Type1": 1.44, "Type2": 0.64, "Type3": 0.20, "Type4": 1.70 }

So the Highcharts data part should become:

 data: [{
      name: 'Type1',
      y: 1.44,
      drilldown: 'Type1'
    },
{
      name: 'Type2',
      y: 0.64,
      drilldown: 'Type2'
    },
{
      name: 'Type3',
      y: 0.20,
      drilldown: 'Type3'
    },
{
      name: 'Type4',
      y: 1.70,
      drilldown: 'Type4'
    }
]

WORK IN PROGRESS :

I tried to build a array called myarray as follows :

var myarray = [];

for (const [a, b] of Object.entries(arr)) {
  myarray.push("{name:'" + a + "', y:" +b + ", drilldown:'" + a + "'}")
}

It returns :

["{name:'Type1', y:1.44, drilldown:'Type1'}", "{name:'Type2', y:0.64,
drilldown:'Type2'}", "{name:'Type3', y:0.2, drilldown:'Type3'}",
"{name:'Type4', y:1.7, drilldown:'Type4'}"]

… that does not completely fit to the Highcharts syntax. I tried it…

    data: [
      myarray
    ]

… and it indeed fails. Maybe it’s because of the apostrophes ?
Do you how to correct it to make the chart work ?
Please see my tries on that JSFiddle.

Any help would be very appreciated, thanks !

2

Answers


  1. I don’t know the library you are using but I realize that the syntax that data expects is an Array< Object> and you are building the variable myArray as an Array< string>.
    I suggest changing the code snippet:

    for (const [a, b] of Object.entries(arr)) {
      myarray.push("{name:'" + a + "', y:" +b + ", drilldown:'" + a + "'}")
    }
    

    for:

    for (const [a, b] of Object.entries(arr)) {
      myarray.push({name: a, y:b , drilldown:a })
    }
    

    then data can receive myArray like this:

    data: myarray
    
    Login or Signup to reply.
  2. You need to create an array of objects, not an array of strings. For example:

    for (const [a, b] of Object.entries(arr)) {
      myarray.push({
        name: a,
        y: b,
        drilldown: a
      })
    }
    
    Highcharts.chart('container', {
      series: [{
        ...,
        data: myarray
      }],
      ...
    });
    

    Live demo: https://jsfiddle.net/BlackLabel/bhsw42r9/

    API Reference: https://api.highcharts.com/highcharts/series.column.data

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search