Using a variable as an object property’s name and ES6's ComputedPropertyName

So I’m working on a personal project that — long story short — involves populating a javascript object with relevant fantasy football-player-related data (because why not?!). I’m playing around with a cool React Charting library that allows you to input data, and then it’ll spit out whatever type of chart tickles your fancy (bar chart, line chart, pie chart, etc.).

So I’m feeding the relevant data into the React component to be used as props, and that data prop type is an array. Each object in this array is going to represent a specific bar in the chart, so to speak. A slice of that array looks like this (notice the player name):

const barChartData = [
{name: 'Fantasy Pts', Julio Jones: playerSeasonStats.FantasyPoints, 'Top 8 Average': topWrAverage.fantasyPoints}]

However, this data needs to be composable and resuable, so I can’t really populate it with individual player names (such as “Julio Jones” above). More specifically, this React component has a particular prop that represents the player name that I want to use as the key of the object. In other words, I want to use a dynamic key name when declaring an object property. Luckily, ECMAScript 2015 allows me to do so, by using ES6's ComputedPropertyName. So now, after declaring a property name as a variable, I can then use that name as an Object’s key like so:

var playerName = props.searchedPlayer.name;
var barChartData = [
{name: 'Fantasy Pts', [playerName]: playerSeasonStats.FantasyPoints, 'Top 8 Average': topWrAverage.fantasyPoints}]

So instead of having to worry about populating the object with individual player names, I can use the props that have already been passed into my React component and specify the relevant one to sub in as the bar chart’s player name. Cool stuff!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.