Computed Property Names In JavaScript
As of ES6, JavaScript now supports using computed property names directly in objects. When defining object properties with constants or variables, this can make code easier to read. To understand this, compare these 2 implementations of toObject:
function toObjectLong(key, value) { const obj = {}; obj[key] = value; return obj; } function toObject(key, value) { return { [key]: value }; } console.log(toObjectLong('hp', 100)); // { hp: 100 } console.log(toObject('hp', 100)); // { hp: 100 }
To see where this is useful, the above can be built upon. Below is a function that is given an array of array values and a list of keys. That way the property values do not have to be defined with the initial data. Which could be useful for UIs where users can give data custom property names:
function createCarsObj(cars, key1, key2) { const carObj = {}; for (let car of cars) { carObj[car[0]] = { [key1]: car[1], [key2]: car[2] }; } return carObj; } const carData = [ ['miata', 155, 2400], ['elise', 217, 2000], ['alfaromeo', 237, 2465] ]; console.log(createCarsObj(carData, 'hp', 'weight')); // { miata: { hp: 155, weight: 2400 }, // elise: { hp: 217, weight: 2000 }, // alfaromeo: { hp: 237, weight: 2465 } }
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/computedPropertyNames.js