How to access an array of objects with tooltip.format() from anychart.js

469 Views Asked by At

I am having trouble trying to present an array of objects on the tooltip of an Anychart.js map. I understand that we can access the dataset by doing something like: %[name of property in data set]. My data set has the following form:

{
    "country": "Austria",
    "id": "AT",
    "continent": "Europe",
    "songs": [
        {
        "rank": 33,
        "title": "Stuck with U (with Justin Bieber)",
        "artists": "Ariana Grande, Justin Bieber",
        "album": "Stuck with U",
        "explicit": 0,
        "duration": "3:48"},
        {
        "rank": 34,
        "title": "Late Night",
        "artists": "Luciano",
        "album": "Late Night",
        "explicit": 0,
        "duration": "3:20"
        },
        ... more objects
        ]
    }
}

If I wanted to access the Country property I would simply add it to the tooltip by doing:

tooltip.format("Country: " + {%country});

The issue is when trying to access an array of objects, I have tried different variations and none of them worked. Trying to show the title of every song:

tooltip.format({%songs}.{%title});
tooltip.format({%songs.%title});
tooltip.format({%songs}[{%title}]);

I also saw in the documentation that we can send a function as argument so I tried the following where I would concatenate every title of the collection but did not succeed either:

tooltip.format(function() {
  let concatenated = '';
  this.songs.forEach(song => {
    concatenated += song + ' ';
  });
  return concatenated;
});

I would really appreciate your help guys.

2

There are 2 best solutions below

0
On BEST ANSWER

String tokens do not support nested objects/properties. But you can use the callback function of the formatted to get access to songs. The context prototype includes getData() method provides that. Like this:

  series.tooltip().format(function() {
    console.log(this.getData('songs'));
    return 'tooltip';
  });

For details, check the live sample we prepared.

0
On

In case any one else is looking for a solution to this answer. I figured out how to loop through an embed array, and call on specific information.

  chart.edges().tooltip().format(function () {
    var format = ''
    var songs = this.getData('songs');
    songs.forEach(function (data, builtin, dom) {
      format = '<p>'+data['title']+' by '+data['artists']+'&nbsp;</span></p>' + format
    });
    console.log(format)
    return format
  });