Giter Site home page Giter Site logo

notes-es6-destructuring's Introduction

ES6: Array & Object destructuring

Contenido


Intro

Es una forma concisa de extraer valores individuales ("desestructurar") de arrays y otros objetos y guardarlos en variables.

↑ Ir al inicio

Object destructuring

Usando destructuring, vamos a crear variables con los mismos nombres que las propiedades del objeto y guardar en estas sus valores.

⚠️ el orden de los elementos no importa, sólo que matcheen los nombres de las propiedades

// before destructuring 😢
const name = user.fullName;
console.log(name); // 'Sam Fisher';

// after destructuring 😍
const { fullName } = user;
console.log(fullName) // 'Sam Fisher';
// The old way 😱
const fullName = user.fullName;
const age = user.age;
const job = user.job;
console.log(fullName, age, job); // 'Sam Fisher' 62 'spy'

// The destructuring way 😎
const { fullName, age, job } = user;
console.log(fullName, age, job); // 'Sam Fisher' 62 'spy';

↑ Ir al inicio

Extraer valores de objetos pasados como parámetros de una función

Los nombres que usemos para los parámetros deben coincidir con nombres de propiedades del objeto que se recibe, sino van a tener undefined como valor

// ES5
function myFunc(opts) {
  var name = opts.name;
  var age = opts.age;
}

myFunc({ name: 'John', age: 25 });
// ES6
function myFunc({ name, age }) {
  // your code ✨
}

↑ Ir al inicio

Renombrar valores extraídos (aka alias/custom names)

En parámetros recibidos en funciones

function myFunc({ someLongPropertyName: prop }) {
  console.log(prop);
}

myFunc({ someLongPropertyName: 'Hello' })
// logs 'Hello'

↑ Ir al inicio

Extrayendo valores a constantes/variables

const user = {
  fullName: 'Sam Fisher',
  age: 62,
  job: 'spy'
}

const { fullName } = user;
fullName;     // =>'Sam Fisher'

// assign `completeName` alias to `fullName` bind
const { fullName: completeName } = user;
completeName; // => 'Sam Fisher'

↑ Ir al inicio

Default values

El destructuring nos permite asignar valores por default a una variable, en el caso de que no reciba ningún valor ó este sea undefined.

const { name = 'Sam' } = user;
console.log(name); // Sam

También funciona con arrays

const array = [1];

const [one, two = 2] = array;

↑ Ir al inicio

Arrays

⚠️ el orden de los elementos importa

// without destructuring 😱
const array = [1, 2, 3, 4, 5];

const one = array[0];
const two = array[1];

En vez de definir variables, lo que hacemos con destructuring es crear un array de variables. El índice de estas variables se corresponde con el índice de los elementos en el array que estamos mapeando.

// with destructuring 😎
const array = [1, 2, 3, 4, 5];
// `one` will take the array[0] value and `two` the array[1] value
const [one, two] = array;

console.log(one, two);
// skip some numbers
const array = [1, 2, 3, 4, 5];
const [,, three] = array;

console.log(three);

↑ Ir al inicio

Retornar y extraer múltiples valores

const sumAndMultiply = (a, b) => [a + b, a * b];

const [sum, product] = sumAndMultiply(2, 3);

↑ Ir al inicio

Swapping de variables

// element swapping without aux ✨
let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a);
console.log(b);

↑ Ir al inicio

Destructuring + Rest parameters magic ✨

También podemos quedarnos con el primer valor de un array usando destructuring y guardar el resto en otro array. El rest operator (...) nos permite referenciar a estos elementos restantes.

⚠️ para que esto funcione, el operador de los 3 ... (similar a cuando usamos spread, pero en este caso lo llamamos rest parameters) sólo puede asignarse al último elemento al que aplicamos destructuring (porque es el resto, lo restante, rest... se entiende? Acá podés leer más sobre rest parameters)

const numbers = [ 10, 20, 30, 40, 50 ];
// array destructuring + rest operator
const [ head, ...tail ] = numbers;

↑ Ir al inicio

...y con objetos

Podemos usar el rest operator para crear un objeto con las propiedades restantes.

const eBook = { 
  title: 'The Lord of the Rings - The Fellowship of the Ring', 
  genre: 'Fantasy', 
  author: 'J. R. R. Tolkien', 
  cover: 'https://i.imgur.com/OwMUnQu.jpg'
}

const {title, ...info} = eBook;

En el ejemplo anterior, el objeto info sería equivalente a

const info = {
  genre: 'Fantasy', 
  author: 'J. R. R. Tolkien', 
  cover: 'https://i.imgur.com/OwMUnQu.jpg'
}

↑ Ir al inicio

Compatibilidad con los diferentes browsers

La sintaxis de destructuring funciona en todos los navegadores modernos (incluyendo mobile), pero no tiene soporte en IE.

El rest operator no funciona en Edge ni Safari (aunque Edge tendrá soporte cuando salga la beta con Chromium).

No podemos usar polyfills con destructuring.

👉 Como siempre, se recomienda visitar Can I use... para estar al tanto de las novedades en cuanto al soporte de una determinada feature.

↑ Ir al inicio

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.