Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,735 Points

ES6 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
I Dilate
3,983 Points

Hi 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
I Dilate
3,983 Points

Computed Property Names