Skip to content

Instantly share code, notes, and snippets.

@sparker888
Last active October 25, 2022 14:45
Show Gist options
  • Save sparker888/fd0d0b07525583c626dbc061a0d5fc38 to your computer and use it in GitHub Desktop.
Save sparker888/fd0d0b07525583c626dbc061a0d5fc38 to your computer and use it in GitHub Desktop.
Object Destructuring

Object Destructuring

The object and array literal expressions provide an easy way to create ad hoc packages of data.

const x = [1, 2, 3, 4, 5];

The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.

const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2

Similarly, you can destructure objects on the left-hand side of the assignment.

const obj = { a: 1, b: 2 };
const { a, b } = obj;
// is equivalent to:
// const a = obj.a;
// const b = obj.b;

Object Destructuring in React

In React, you can use object destructuring to extract props from a component.

const MyComponent = ({ name, age }) => {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
};

Object Destructuring in React useState

Example 1:

function App() {
    const [num, setNum] = useState(0);
}

Example 2:

function App() {
    const [state, setState] = useState({
        name: "John",
        age: 32,
    });
    
    const { name, age } = state;
    
    return (
        <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
        </div>
    );
}

Object Destructuring in React useEffect

function App() {
    const [state, setState] = useState({
        name: "John",
        age: 32,
    });
    
    const { name, age } = state;
    
    useEffect(() => {
        console.log(name);
    }, [name]);
    
    return (
        <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
        </div>
    );
}

More examples

Array destructuring

Basic variable assignment.

const foo = ['one', 'two', 'three'];
console.log(red); // "one"
console.log(green); // "two"
console.log(blue); // "three"

Destructuring with more elements than the source

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N, only the first N variables are assigned values. The values of the remaining variables will be undefined.

const foo = ['one', 'two', 'three'];

const [red, green, blue, yellow, purple] = foo;
console.log(red); // "one"
console.log(green); // "two"
console.log(blue); // "three"
console.log(yellow); // undefined
console.log(purple); // undefined

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

function f() {
  return [1, 2];
}

const [a, b] = f();
console.log(a); // 1
console.log(b); // 2

Ignoring some returned values

You can ignore some returned values by using commas.

function f() {
  return [1, 2, 3];
}

const [a, , b] = f();
console.log(a); // 1
console.log(b); // 3

const [c] = f();
console.log(c); // 1

You can also ignore all returned values by using commas.

function f() {
  return [1, 2, 3];
}

const [,,] = f();

You can assign the remainder of an array to a variable using the rest syntax.

const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]

Object destructuring

Basic assignment

const o = { p: 42, q: true };
const { p, q } = o;

console.log(p); // 42
console.log(q); // true

Assigning to new variable names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

const o = { p: 42, q: true };
const { p: foo, q: bar } = o;

console.log(foo); // 42
console.log(bar); // true

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo.

This is especially helpful when dealing with name collisions, or in working with names that are not valid variable names.

Assigning to new variable names and providing default values

A property can be both

- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is undefined.
const { a: aa = 10, b: bb = 5 } = { a: 3 };

console.log(aa); // 3
console.log(bb); // 5

NOTE: You can also unpack properties from nested objects.

const metadata = {
  title: 'Scratchpad',
  translations: [
    {
      locale: 'de',
      localization_tags: [],
      last_edit: '2014-04-14T08:43:37',
      url: '/de/docs/Tools/Scratchpad',
      title: 'JavaScript-Umgebung'
    }
  ],
  url: '/en-US/docs/Tools/Scratchpad'
};

let {
  title: englishTitle, // rename
  translations: [
    {
      title: localeTitle, // rename
    },
  ],
} = metadata;

console.log(englishTitle); // "Scratchpad"


console.log(localeTitle);  // "JavaScript-Umgebung"

Destructuring in Loops

Array destructuring in For Loops

NOTE: This is awesome when you have an array of objects

const people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

for (const { name: n, family: { father: f } } of people) {
  console.log('Name: ' + n + ', Father: ' + f);
}

// "Name: Mike Smith, Father: Harry Smith"

// "Name: Tom Jones, Father: Richard Jones"

Destructuring in Functions

You can destructure objects and arrays as arguments in function calls.

function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
  console.log(size, cords, radius);
  // do some chart drawing
}

drawES2015Chart({
  cords: { x: 18, y: 30 },
  radius: 30
});

Swapping variables

let a = 1;
let b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Note: This is a common interview question

Desctructuring in Regular Expressions

const url = 'https://developer.mozilla.org/en-US/Web/JavaScript';

const parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);

const [, protocol, fullhost, fullpath] = parsedURL;

console.log(protocol); // "https"
console.log(fullhost); // "developer.mozilla.org"
console.log(fullpath); // "en-US/Web/JavaScript"

Destructuring with Dynamic Properties

const key = 'z';
const { [key]: foo } = { z: 'bar' };

console.log(foo); // "bar"

Note: Here we're using a computed properties in destructuring just like you can in object literals. By wrapping the property value in brackets like [key] it now takes a variable as it's value instead of a static name. In other words, it's computed at runtime. You follow it with a colon [key]: foo to provide it with a static variable name to use in your code.

For more information, see Destructuring on MDN.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment