Destructuring objects

Destructuring allows you to bind a set of variables to a corresponding set of values anywhere that you can normally bind a value to a single variable.

It helps pull incoming objects apart.

  1. var address = {
  2. city: "Costa Mesa",
  3. state: "CA",
  4. zip: 92444
  5. };
  6. let {city, state, zip} = address;
  7. log(city); // 'Costa Mesa'
  8. log(state); // 'CA'
  9. log(zip); // 92442

Alias

Or we can use alias:

  1. var address = {
  2. city: "Costa Mesa",
  3. state: "CA",
  4. zip: 92444
  5. };
  6. let {city: c, state: s, zip: z} = address;
  7. log(c, s, z); // 'Costa Mesa CA 92444'

Simpler way

You can also use it like

  1. var person = {name: 'Aaron', age: 35};
  2. displayPerson(person);
  3. function displayPerson({name, age}) {
  4. // do something with name and age to display them
  5. }

Default values

You can pass default values

  1. var person = {name: 'Aaron', age: 35};
  2. displayPerson(person);
  3. function displayPerson({name = "No Name provided", age = 0}) {
  4. // do something with name and age to display them
  5. }

Irrefutable pattern

The destructuring must match the object or else it will throw an error.

  1. var person = {name: 'Aaron', age: 35};
  2. let {name, age, address} = person; // throws! (irrefutable)
  3. let {name, age, ?address} = person; // is ok because we specified address as undefineable (refutable)
  4. let ?{name, age, address} = person; // Forgives the whole pattern

All patterns

  1. let {a: x} = {} // throw
  2. let ?{a: x} = {} // x = undefined
  3. let ?{a: x} = 0 // x = undefined
  4. let {?a: x} = {} // x = undefined
  5. let {?a: x} = 0 // throw

Patterns w/ Default Values

  1. let ?{a: x = 1} = undefined // x = 1
  2. let {?a: x = 1} = undefined // throw
  3. let {?a: x = 1} = {} // x = 1

Patterns - Nested

  1. let person = {
  2. name: "Aaron",
  3. age: "35",
  4. address: {
  5. city: "Salt Lake City",
  6. state: "UT",
  7. zip: 84115
  8. }
  9. };
  10. let {name, age, address: {city, state, zip}} = person; // this won't create address, but will create city, state, zip