Skip to content

Instantly share code, notes, and snippets.

@hardikpthv
Last active September 20, 2018 06:56
Show Gist options
  • Save hardikpthv/9da8365a558d12781547f9210f7a24c2 to your computer and use it in GitHub Desktop.
Save hardikpthv/9da8365a558d12781547f9210f7a24c2 to your computer and use it in GitHub Desktop.
Object Destructuring even better with ES2018
const hero = {
id: 1,
name: "Thor",
powers: [
"Teleportation",
"Master Combatant",
"Superhuman Stamina",
"Self-sustenance"
],
weapon: "Mjolnir",
place: {
current: 'Earth',
native: 'Asgard'
}
};
console.info(hero);
/*
Output:
{
id: 1,
name: "Thor",
powers: [
"Teleportation",
"Master Combatant",
"Superhuman Stamina",
"Self-sustenance"
],
weapon: "Mjolnir",
place: {
current: 'Earth',
native: 'Asgard'
}
};
*/
//Extract properties(name and weapon) from hero.
const { name, weapon } = hero;
console.info(name);
/*
Output: Thor
Equivalent to: hero.name
*/
console.info(weapon);
/*
Output: Mjolnir
Equivalent to: hero.weapon
*/
//Extract properties and assign new name.
const { name: heroName, weapon: heroWeapon } = hero;
console.info(heroName);
/*
Output: Thor
Equivalent to:
let heroName = hero.name
*/
console.info(heroWeapon);
/*
Output: Mjolnir
Equivalent to:
let heroWeapon = hero.weapon
*/
//Set default value while extracting.
const { name = "Heimdall", brother = "Loki" } = hero;
console.info(name);
/*
Output: Thor
Why: 'Thor' is from the original object. If it was not present then value could be 'Heimdall'
*/
console.info(brother);
/*
Output: Loki
Equivalent to: hero.brother = !hero.brother ? 'Loki' : hero.brother;
*/
// Extract from nested object/array
const {
powers: [thorFirstPower],
place: { native }
} = hero;
console.info(`thorFirstPower: ${thorFirstPower}`); //Output: Teleportationuniverse
console.info(`native: ${native}`); //Output: Asgard
/*
Extract some individually and others in the group using "rest(...) operator".
This super cool feature is introduced in ES2018.
*/
const { id, ...remaining } = hero;
console.info(id); //Output: 1
console.info(remaining);
/*
Output:
{
"name": "Thor",
"powers": [
"Teleportation",
"Master Combatant",
"Superhuman Stamina",
"Self-sustenance"
],
"weapon": "Mjolnir",
place: {
current: 'Earth',
native: 'Asgard'
}
}
*/
/*
1) Replace existing properties
2) Merge objects using 'spread(...) operator'
3) Extend object with new propert[y|ies]
*) This super cool feature is also introduced in ES2018.
*/
const updatedHero = {
...hero,
name: 'Thor Odinson',
brother: 'Loki'
};
console.info(updatedHero);
/*
Output:
{
brother: 'Loki'
name: 'Thor Odinson',
...
}
Equivalent to:
const updatedHero = Object.assign(hero, {
name: 'Thor Odinson',
brother: 'Loki'
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment