如何在使用d3.group分组后获取键名数组?
问题描述
已通过d3.group按sport字段对运动员数据完成分组:
athletes = [ {name: "Floyd Mayweather", sport: "Boxing", nation: "United States", earnings: 285}, {name: "Lionel Messi", sport: "Soccer", nation: "Argentina", earnings: 111}, {name: "Cristiano Ronaldo", sport: "Soccer", nation: "Portugal", earnings: 108}, {name: "Conor McGregor", sport: "MMA", nation: "Ireland", earnings: 99}, {name: "Neymar", sport: "Soccer", nation: "Brazil", earnings: 90}, {name: "LeBron James", sport: "Basketball", nation: "United States", earnings: 85.5}, {name: "Roger Federer", sport: "Tennis", nation: "Switzerland", earnings: 77.2}, {name: "Stephen Curry", sport: "Basketball", nation: "United States", earnings: 76.9}, {name: "Matt Ryan", sport: "Football", nation: "United States", earnings: 67.3}, {name: "Matthew Stafford", sport: "Football", nation: "United States", earnings: 59.5} ] athletesBySport = d3.group(athletes, d => d.sport)
需要提取所有分组键(运动项目)组成如下格式的数组(顺序无关):
['Boxing', 'Soccer', 'MMA', 'Basketball', 'Tennis', 'Football']
解决方案
方法1:利用Map的keys()方法 + Array.from()
d3.group返回的是标准的Map对象,Map自带keys()方法可获取所有键的迭代器,通过Array.from()将其转换为数组:
const sportsArray = Array.from(athletesBySport.keys());
方法2:利用扩展运算符...
扩展运算符可直接展开可迭代对象(如Map的键迭代器),快速生成数组:
const sportsArray = [...athletesBySport.keys()];
方法3:直接从原数组提取去重(无需依赖分组结果)
如果不需要保留分组后的Map,也可以直接从原始athletes数组中提取并去重sport字段:
const sportsArray = [...new Set(athletes.map(d => d.sport))];
内容的提问来源于stack exchange,提问作者jtr13
相关产品推荐
相关产品推荐

