Object Destructuring In Javascript
Object destructuring is a convenient way to extract multiple values from objects and arrays. There are some handy ways to deconstruct an object:
You can alias the property to a different variable, or just use the provided object property:
const myObject = {
student: 'Mike',
teacher: 'Susan'
};
const { student: pupil, teacher: prof } = myObject;
console.log(pupil, prof);
> Mike Susan
const { student, teacher } = myObject;
console.log(student, teacher)
> Mike Susan
You can also just pluck the values you want to from an array or an object:
const [one, two] = ['abc', 'xyz', 'foo'];
console.log(one, two);
> 'abc' 'xyz'
When you deconstruct an object it coerces the source to an object before accessing it which means you can access properties of an object
const { length: thelen } = 'xyzabc';
console.log(thelen);
> 6
You can also provide default values in object patterns:
const [x=3] = [];
console.log(x);
> 3
const {foo: x=3, bar: y} = {};
console.log(x);
> 3
console.log(y);
> undefined
You can skip items when deconstructing as well:
const [,, x, y] = ['a', 'b', 'c', 'd'];
console.log(x);
> 'c'
console.log(y);
> 'd'
Let’s cover nested destructuring:
const student = {
name: 'Mike',
grades: {
science: 'A',
math: 'B'
},
classes: ['science', 'math']
};
// we refer to the science property in the student object to obtain the classes
// we grab the first array element and name it subject to obtain the grade
const { grades: { science }, classes: [subject] } = student;
console.log(science)
> 'A'
console.log(subject)
> 'science'
Read more about it here