DEV Community

Cover image for JavaScript object destructuring usages you must know

JavaScript object destructuring usages you must know

Tapas Adhikary on January 18, 2022

Introduction We use JavaScript objects to store data and retrieve it later. We store data(aka information) in key-value pairs. The key-v...
Collapse
 
dagropp profile image
Daniel Gropp • Edited

Nice 😎 this is an amazing and very useful feature. Another useful thing with object destructing is to destruct some properties and then use the spread operator to get the rest.

const obj = {name: β€œMoses”, age: 120, country: β€œEgypt”};
const {name, …rest} = obj;
console.log(name); // β€œMoses”
console.log(rest); // {age: 120, country: β€œEgypt”}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
maxiqboy profile image
Thinh Nguyen • Edited

Since it is ..., it's not sread operator.

In Object Destructuring, these three dots is rest propertises,

Rest in Object Destructuring
The Rest/Spread Properties for ECMAScript proposal (stage 4) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atapas profile image
Tapas Adhikary

Awesome Daniel, Thanks for adding to the list. Have a great day.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ
const str = 'Kumquat'
const {length, [length-1]:last} = str

console.log(length) // 7
console.log(last) // 't'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kazuyastefan profile image
Stefan Grbic

I was playing a bit with at(), but it's not supported in all browsers.

const str = 'Kumquat'
const {length, last = str.split('').at(-1) } = str;

console.log(length) // 7
console.log(last) // 't' 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atapas profile image
Tapas Adhikary

Mindblowing. Thanks, John for sharing.

Collapse
 
prajapatiparth profile image
Parth Prajapati

Here's one more for you.

// using destructuring to optionally add properties to object;

const isEmployee = true;

const person = {
  name: 'xyz',
  age: 28,
  ...isEmployee ? {     // if isEmployee is true, it will destructure the employee object
    employeeId: 'G548',
    department: 'procurement'
  } : {},   // else it will destructure this empty object
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atapas profile image
Tapas Adhikary

Super. Thanks!

Collapse
 
mrdulin profile image
official_dulin • Edited

A lot of times, you don't need destructuring. Reasons:

  1. Avoiding variable conflicts
  2. Keep context and enhance readability
Collapse
 
atapas profile image
Tapas Adhikary

You can use aliases for the # 1 point.

2, agree but when you see the entire dev ecosystem(like with React I see) using it, I think, it is better to contribute that way.

Hey, thanks a lot for giving it a read and posting your views.

Collapse
 
froxx93 profile image
Froxx93

I would advise against variable definitions during destructing like this:

const {name, dept, message = `${name} is ${dept}`} = employee;
Enter fullscreen mode Exit fullscreen mode

What you're actually doing here is simply defining a default value for employee's property message. So as a side effect if your object actually has a property with that name, it will simply override your default value.

const employee = {
  name: 'John',
  dept: 'Service',
  message: 'This is me!'
}
const {name, dept, message = `${name} is ${dept}`} = employee;
console.log(message); // logs 'This is me!'
Enter fullscreen mode Exit fullscreen mode

It works, and you could still use it, but be aware of what's actually happening and consider writing 1 line of extra code to prevent possible unexpected behaviour.

Apart from that – A good overview to destructing. Gj!

Collapse
 
olsard profile image
olsard

Great! Thanks for sharing.

Collapse
 
atapas profile image
Tapas Adhikary

Welcmome πŸ˜€

Collapse
 
jackmcbride98 profile image
Jack McBride

Hi just testing the comment indentation levels on dev.to

Thread Thread
 
atapas profile image
Tapas Adhikary

Test passed? πŸ˜…

Thread Thread
 
jackmcbride98 profile image
Jack McBride

I'm building a blog site and im in the process of adding nested replies to comments, I wanted to see how the ui here handled nested comments. I wonder how far down you can go and will it keep indenting

Thread Thread
 
jackmcbride98 profile image
Jack McBride

12

Collapse
 
phyberapex profile image
PhyberApex

Awesome article! I use destruction all the time. Two things I find confusing tho is that nesting and alias share the colon operator (if you look closely they differ in syntax but I find it confusing). Same with default value and assignment to new attribute. So if you want to create a new attribute you need to make sure that one does never already exist on the object or you might get unwanted results.

~Cheers

Collapse
 
atapas profile image
Tapas Adhikary

Thank you! I completly agree.

Collapse
 
8bitsouvik profile image
Souvik Mandal

Thanks for elaborating destructuring in loops and and default value.πŸ˜ƒ
It'll help me to improve my current project

Collapse
 
atapas profile image
Tapas Adhikary

That's great. Very glad to know, you found it helpful

Collapse
 
gauravchandra profile image
Gaurav Chandra

Agree. The code needs to be human readable rather than concise. In any case the code gets compiled to a shorter form during build.

Collapse
 
lincoln_zhu profile image
Lincoln Zhu

Awesome post

Collapse
 
atapas profile image
Tapas Adhikary

Thank you very much!