Sometimes you may want to initialize an object by setting the property names dynamically using strings
defined somewhere else. You can use the ES6’s Computed property names for this, in this quick tips episode,
you will learn how. Above is the vid and below you will find some useful notes.
- 1.
Pre-reqs
-
Have a browser like Chrome, Edge or Firefox installed
-
- 2.
Using Computed Property Names in Javascript
-
Initialize and Object with a computed property name
const fieldName = 'creature'; let myObject = { [fieldName]: '🐉' };
-
Getting the values from the object using the dot or the bracket notation
console.log(myObject.creature); console.log(myObject[fieldName]);
-
A more complex example of computed property names
let stuff = { ['food' + 1]: '🍌', ['something'.toUpperCase() + 1 + '_function' + 2]: () => '🏺' } console.log(stuff.food1); console.log(stuff.SOMETHING1_function2());
-
Defining Class methods and getters or setters using computed property names
const aDynamicMethodName = 'weirdHuh', aDynamicPropertyName = 'something'; class SomethinInteresting { [aDynamicMethodName]() { console.log('Interesting way of naming methods'); } get [aDynamicPropertyName]() { return 'a dynamic getter name is born!'; } }
-
Calling the methods or getters using the dot or the bracket notation
const myNewObject = new SomethinInteresting(); myNewObject[aDynamicMethodName](); myNewObject.something;
-
- 3.
Comentarios
Publicar un comentario