
Brendan Whiting
Front End Web Development Treehouse Moderator 82,128 PointsES6 key assignment? Can't remember name of this feature
I vaguely remember there's a new feature in ES6 where I can dynamically assign the key of an object from the name of a variable, using square brackets. Something like:
let object = { [keyname]: value }
I can't find it on google because I can't remember what the feature is called.
Here is my use case btw:
I have some code where I'm repeating certain logic to pass an object into a method. It would be great if I could make a generic helper function to factor this out, but when I tried that I couldn't figure out how to have the key of the object computed dynamically.
updateSearchOrigin(latlng: LatLng) {
const searchOrigin = mapLatLngToGeoPoint(latlng);
this.userDataRef
.update({ searchOrigin })
.catch(error => {
this.userDataRef.set({ searchOrigin })
});
}
updateSearchDestination(latlng: LatLng) {
const searchDestination = mapLatLngToGeoPoint(latlng);
this.userDataRef
.update({ searchDestination })
.catch(error => {
this.userDataRef.set({ searchDestination })
});
}
updateTimeTarget(searchTimeTarget: string) {
this.userDataRef
.update({ searchTimeTarget })
.catch(error => {
this.userDataRef.set({ searchTimeTarget })
});
}
updateDatetime(date: string) {
const searchDatetime = new Date(date);
this.userDataRef
.update({ searchDatetime })
.catch(error => {
this.userDataRef.set({ searchDatetime })
})
}
2 Answers

I Dilate
3,974 PointsHi Brendan,
That's right, in ES6 you can use a variable to define a key name in an object using the square brackets, as per your example...
const keyName = "manufacturer";
carObject = {
[keyName]: "Toyota"
};
console.log(carObject.manufacturer); // Will output "Toyota" to your console

I Dilate
3,974 PointsComputed Property Names
Brendan Whiting
Front End Web Development Treehouse Moderator 82,128 PointsBrendan Whiting
Front End Web Development Treehouse Moderator 82,128 PointsWhat's the official name of this ES6 feature?