Search code examples
javascriptanychartanychart-8.2

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


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.


Solution

  • 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.