DEV Community

Fatima Alam
Fatima Alam

Posted on • Edited on

De-structuring Objects

Object to be destructured ->

Both of these are ways to de-structure objects ({}) and specifically equating them

In this openingHours is already defined as an object itself outside restaurant

This is making an object fri which further has a variable open called as o and close called as c.

The Spread Operator ->

const arr = [7, 8, 9];
const badNewArr = [1, 2, arr[0], arr[1], arr[2]];
console.log(badNewArr);

const newArr = [1, 2, ...arr];
console.log(newArr);
console.log(...newArr);
Enter fullscreen mode Exit fullscreen mode

Output ->

Last console gives de-structured output.

const arr = [7, 8, 9];
const badNewArr = [1, 2, arr[0], arr[1], arr[2]];
console.log(badNewArr);

const newArr = [1, 2, ...arr];
console.log(newArr);
console.log(...newArr);
console.log(1, 2, 7, 8, 9);

Output ->


const restaurantCopy = {...restaurant};
restaurantCopy.name = 'Ristorante Roma';
console.log(restaurantCopy.name);
console.log(restaurant.name);
Enter fullscreen mode Exit fullscreen mode

Output ->

Rest Pattern and Parameters

when we want to assign a value to a variable (spread operator on LHS)

const [a, b, ...others] = [1, 2, 3, 4, 5];
console.log(a, b, others);
Enter fullscreen mode Exit fullscreen mode

Output ->

This rest can be used with only 1 variable at a time
->else it would create a mess

For the object

It first searches for "sat" variable in the opening hours object and then assigns the rest in the weekdays. It merges the keys "sat" (from LHS) and "sat" (from RHS) in openingHours and whatever left is put in "weekdays".

This can also be used as an argument where we don't know the of arguments

For loops

specifying key and value pair de-structuring just like the object

Top comments (0)