Four Kitchens
Insights

A practical introduction to ES2015 Objects

2 Min. ReadDevelopment

With es2015, Object Literals get a fairly hefty set of new features that make data manipulation much more readable and succinct.

At the moment, not all of these features are available in all environments, but we’re not here to talk about feature support. Instead, we’re making the assumption that they are available in your environment or you’re using a tool like Babel to transform your JavaScript.

__proto__

Access to Object.prototype.__proto__ getters and setters is now standardized!

var hello = {
  speak: () => 'hello'
};

var helloWorld = {
  __proto__: hello
};

helloWorld.speak()
"hello"

super

super provides access to properties on the prototype.

var hello = {
  speak: () => 'hello'
};

var helloWorld = {
  __proto__: hello,
  speak() {
    return super.speak() + ' world!';
  }
};

helloWorld.speak()

Shorthand Property Assignment

Putting the name of an object in an object literal without a corresponding colon and value will use the name of the object as the key and its value as the value.

Computed Property Names

var strangers = [
  {
    name: 'Star Lord'
  },  
  {
    name: 'Adam Warlock'
  }
];

function makeGuardians(people) {
  var affiliation = 'Guardians of the Galaxy';
  return people.map((person) => ({
    name: person.name,
    affiliation
  }));
}

makeGuardians(strangers);

Property names enclosed in square brackets are now computed.

var unformatted = {
  'thisIsFine': 'but',
  'people-still-do-this': 'and I don't know why'
};

function format(object, property) {
  var temp = object[property];
  delete object[property];
  return Object.assign({}, object, {
    [_.camelCase(property)]: temp
  });
}

format(unformatted, 'people-still-do-this');

Spreads

Spreads within object literals work similarly to Object.assign: all enumerable properties are applied to the new object with later declarations overwriting previous declarations.

var optionsOne = {
  offset: 13
};

var optionsTwo = {
  start: 0,
  end: 5
};

var a = {
  ...optionsOne,
  ...optionsTwo,
  end: 10
};

Hopefully this gives you a running start with the new Object features in ES2015!