问题描述
我在尝试在 Anychart.js 地图的工具提示上显示一组对象时遇到问题。我知道我们可以通过执行以下操作来访问数据集:%[数据集中的属性名称]。我的数据集具有以下形式:
{
"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","duration": "3:20"
},... more objects
]
}
}
如果我想访问 Country 属性,我只需通过执行以下操作将其添加到工具提示中:
tooltip.format("Country: " + {%country});
问题是在尝试访问对象数组时,我尝试了不同的变体,但都没有奏效。试图显示每首歌的标题:
tooltip.format({%songs}.{%title});
tooltip.format({%songs.%title});
tooltip.format({%songs}[{%title}]);
我还在文档中看到我们可以发送一个函数作为参数,所以我尝试了以下方法,我将连接集合的每个标题,但也没有成功:
tooltip.format(function() {
let concatenated = '';
this.songs.forEach(song => {
concatenated += song + ' ';
});
return concatenated;
});
我真的很感谢你们的帮助。
解决方法
字符串标记不支持嵌套对象/属性。但是您可以使用格式化的回调函数来访问songs
。上下文原型包括 getData()
方法提供的。像这样:
series.tooltip().format(function() {
console.log(this.getData('songs'));
return 'tooltip';
});
有关详细信息,请查看我们准备的 the live sample。