Today I Learned - Rocky Kev

TIL Destructuring a array

POSTED ON:

TAGS:

Another post about destructuring! I love destructuring and I keep forgetting how to use it effectively.


const heroes = [{
firstName: "Clark",
lastName: "Kent",
heroName: "Superman",
species: "Kryptonian",
age: 34
},
{
firstName: "Diane",
lastName: "Prince",
heroName: "Wonder Woman",
species: "Amazonian",
age: 800
},
{
firstName: "Bruce",
lastName: "Wayne",
heroName: "Batman",
species: "Human",
age: 30
}];

How to get:

// I only want Clark
const [{firstName},] = heroes; // Clark

// I only want Batman
const [, , {heroName} ] = heroes; // Batman

// I want everyone's hero names
// ['Superman', 'Wonder Woman', 'Batman']
const heroNames = heroes.map(hero => hero.heroName)

// I want all the details about Bruce Wayne
const theBatmanObject = heroes.find(hero => hero.heroName === 'Batman'); // { ... }
const theBatmanArray = heroes.filter(hero => hero.heroName === 'Batman'); // [{ ... }]

Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.