TIL Destructuring a array
POSTED ON:
TAGS: javascript destructuring
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: javascript