DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on • Updated on

De-structuring Objects

Object to be destructured ->

Image description

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

Image description

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

Image description

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 ->

Image description

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 ->

Image description

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

Output ->

Image description

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 ->

Image description

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

For the object

Image description

Image description

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

Image description

For loops

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

Image description

Top comments (0)