Skip to content

Instantly share code, notes, and snippets.

@PriyaBhatt13
Created April 5, 2018 09:02
Show Gist options
  • Save PriyaBhatt13/34e07756dc18c18c37d1abb32918332c to your computer and use it in GitHub Desktop.
Save PriyaBhatt13/34e07756dc18c18c37d1abb32918332c to your computer and use it in GitHub Desktop.
gist to show how destruction works for nested object
// extract single prop with same name
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {name} = user;
console.log(name); //prints: Fred
// extract single prop with different name
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {name: callSign} = user;
console.log(callSign); //prints: Fred
// extract nested prop from object
const user = {
id: 339,
name: 'Fred',
age: 42,
education: {
degree: 'Masters'
}
};
const {education: {degree}} = user;
console.log(degree); //prints: Masters
// if nested object is not available destruction will throw error
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {education: {degree}} = user; // TypeError: Cannot match against 'undefined' or 'null'.
// avoids type error when nested object is not present
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {education: {school: {name} = {}} = {}} = user;
console.log(name); //prints: undefined
// Approach-1 to add default school name
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {education: {school: {name = 'Dunno'} = {}} = {}} = user;
console.log(name); //prints: Dunno
// Approach-2 to add default school name
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {education: {school: {name}} = {school: {name: 'Dunno'}} = user;
console.log(name); //prints: Dunno
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment