одночасне створення нових змінних та призначеня їм значень з іньшого обїекта
Деструктурізація обїекта
const userProfile = {
name: 'tro',
commq: 23,
hass: false
}
const {name, commq, hass} = userProfile
console.log(name); // tro
console.log(commq); // 23
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
isPublic: true,
rating: 8.38,
};
// Деструктуризуємо
const { title, author, isPublic, rating } = book;
// Використовуємо
const accessType = isPublic ? "pulbic" : "private";
const message = `Book ${title} by author ${author} with rating ${rating} is in ${accessType} access!`;
Встановлення значень за замовчанням при деструктуризації
З метою уникнення присвоєння undefined під час деструктуризації неіснуючих властивостей, можна задати змінним значення за замовчуванням, використовуючи знак =. Це значення буде присвоєно тільки у випадку, коли в об'єкті відсутня властивість із таким ім'ям.
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
};
// Додамо зображення обкладинки, якщо вона відсутня в об'єкті книги
const {
title,
author,
coverImage = "<https://via.placeholder.com/640/480>"
} = book;
console.log(title); // "The Last Kingdom"
console.log(author); // "Bernard Cornwell"
console.log(coverImage); // "<https://via.placeholder.com/640/480>"
Перейменування змінної при деструктуризації
const book = {
title: "The Last Kingdom",
author: "Bernard Cornwell",
genres: ["historical prose", "adventure"],
isPublic: true,
rating: 8.38,
};
// Деструктуризуємо
const { title, author: bookAuthor, isPublic, rating: bookRating } = book;
console.log(title); // "The Last Kingdom"
console.log(bookAuthor); // "Bernard Cornwell"
console.log(isPublic); // true
console.log(bookRating); // 8.38
Значення за замовчуванням для переіменованнії змінної
Для цього після нового імені ставимо дорівнює = і вказуємо її значення за замовчуванням. Якщо така властивість існує в об'єкті, у змінну буде присвоєно її значення.
В іншому випадку змінній буде присвоєно значення за замовчуванням.
const book = {
title: "The Last Kingdom",
coverImage:
"<https://images-na.ssl-images-amazon.com/images/I/51b5YG6Y1rL.jpg>",
};
const {
title,
coverImage: bookCoverImage = "<https://via.placeholder.com/640/480>",
} = book;
console.log(title); // "The Last Kingdom"
console.log(bookCoverImage); // "<https://images-na.ssl-images-amazon.com/images/I/51b5YG6Y1rL.jpg>"
Часткова дестриктуризація обїекта
const user = {
name: "Jacob",
age: 32,
email: "j.cob@mail.com",
isOnline: true
};
const { name, isOnline, ...otherProps } = user;
console.log(name); // "Jacob"
console.log(isOnline); // true
console.log(otherProps); // {age: 32, email: "j.cob@mail.com"}
Деструктуризація параметрів
function doStuffWithBook(book) {
const { title, pages, downloads, rating, isPublic } = book;
console.log(title);
console.log(pages);
}
function doStuffWithBook({ title, pages, downloads, rating, isPublic }) {
console.log(title);
console.log(pages);
}
function printUserInfo({ name, age, hobby }) {
console.log(`Name: ${name}, Age: ${age}, Hobby: ${hobby}`);
}
printUserInfo({
name: "Alice",
age: 25,
hobby: "dancing"
}); // Name: Alice, Age: 25, Hobby: dancing
Глибока деструктуризація
const user = {
name: "Jacques Gluke",
tag: "jgluke",
stats: {
followers: 5603,
views: 4827,
likes: 1308,
},
};
const {
name,
tag,
stats: { followers, views, likes },
} = user;
console.log(name); // Jacques Gluke
console.log(tag); // jgluke
console.log(followers); // 5603
console.log(views); // 4827
console.log(likes); // 1308
Деструктурізація масива
const fruts = ['apple','banana'] const [fruts1, fruts2] = fruts
Значення за замовчанням для масива
Якщо змінних оголошено більше, ніж елементів масиву, їм буде присвоєно undefined. Щоб запобігти цьому, можна вказувати значення за замовчуванням.
const color = [200, 100, 255];
const [ red, green, blue, alfa = 0.3 ] = color;
console.log(rgba(${red}, ${green}, ${blue}, ${alfa})); // “rgba(200, 255, 100, 0.3)"
serProfile) </code>
Часткова деструктуризація масива
Деструктуризуючи масив, можна розпакувати перші необхідні елементи і присвоїти іншу частину елементів масиву змінній, використовуючи операцію …rest.
const color = [200, 255, 100]; const [ red, ...otherColors ] = color; console.log(red); // 200 console.log(otherColors); // [255, 100]
Пропуск значень при дестриктуризації масива
const rgb = [200, 100, 255];
const [, , blue] = rgb;
console.log(`Blue: ${blue}`); // "Blue: 255"
Обмін місцями значень у змінних
[x,y]=[y,x]