Destructing an object in Javascript(Coffee time article)
Hello everyone,
Recently I was reading a good article(as always) by Kent C. Dodds. In destructing part, he was asking for a code change that will make the object destructing in one line. I am sharing his question and my solution to that. I think it can be beneficial to someone else.
function nestedArrayAndObject() {
// refactor this to a single line of destructuring...
const info = {
title: 'Once Upon a Time',
protagonist: {
name: 'Emma Swan',
enemies: [
{name: 'Regina Mills', title: 'Evil Queen'},
{name: 'Cora Mills', title: 'Queen of Hearts'},
{name: 'Peter Pan', title: `The boy who wouldn't grow up`},
{name: 'Zelena', title: 'The Wicked Witch'},
],
},
}
// const {} = info // <-- replace the next few `const` lines with this
const title = info.title
const protagonistName = info.protagonist.name
const enemy = info.protagonist.enemies[3]
const enemyTitle = enemy.title
const enemyName = enemy.name
return `${enemyName} (${enemyTitle}) is an enemy to ${protagonistName} in "${title}"`
}
The part we will change is const {} = info;
. And here is my solution.
const {title,protagonist: {name:protagonistName, enemies:[,,{name:enemyName,title: enemyTitle}] }} = info
Stay healthy, and keep coding for good.