Example 1: javascript object destructuring
let obj = {name: 'Max', age: 22, address: 'Delhi'};
const {name, age} = obj;
console.log(name);
console.log(age);
console.log(address);
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
console.log(b);
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
Example 2: object destructuring into this
const demo = { nextUrl: 'nextUrl', posts: 'posts' };
const target = {};
({ nextUrl: target.nextUrl, posts: target.communityPosts } = demo);
console.log(target);
Example 3: object destructuring
const book = {
title: 'Ego is the Enemy',
author: 'Ryan Holiday',
publisher: {
name: 'Penguin',
type: 'private'
}
};
const {title: bookName = 'Ego', author, name: {publisher: { name }} = book, type: {publisher: { type }} = book } = book;
Example 4: Object destructuring
Object Destructuring =>
The destructuring assignment syntax is a JavaScript expression that makes it
possible to unpack values from arrays,
or properties from objects, into distinct variables.
example:
const user = {
id: 42,
is_verified: true
};
const {id, is_verified} = user;
console.log(id);
console.log(is_verified);
Example 5: mdn destructuring
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y);
console.log(z);
Example 6: mdn destructuring
let a, b;
[a, b] = [1, 2];
console.log(a);
console.log(b);