DEV Community

Cover image for Pick the best parts of an object
Bernard Baker
Bernard Baker

Posted on

Pick the best parts of an object

When you simply want to pick parts of an object. No matter how complex.

Q: I asked my self... I want the value of that's properties - property. How can I get that?

A: Destructuring an object.

Resources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring.

const object = {price: 42, qId: true};
const {price, qId} = object;

console.log(price); // 42
console.log(qId); // true 
Enter fullscreen mode Exit fullscreen mode

The above example is a simple one. The one below is slightly more complex.

let object = {price: 42, qId: {rate: {sId:"foo"}, tracked:false}, uId: 10};
let {price, qId:{rate:{sId} } }= object;

console.log(price); // 42
console.log(qId); // {rate: {sId:"foo"}, tracked: false}
console.log(rate); // {sId:"foo"} 
console.log(sId); // "foo"
Enter fullscreen mode Exit fullscreen mode

If you have any destructuring 🧰 tips, share them below.

Discussion (3)

Collapse
tomekbuszewski profile image
Tomek Buszewski

Hey, just a tip: use meaningful variables names. Nobody knows what o, p etc. means. It really increases readability and understanding :-)

Also, deconstructing is one of my favorite things in JavaScript right now.

Collapse
bernardbaker profile image
Bernard Baker Author

@tomekbuszewski thanks for the tip. I've renamed the variables to be more meaningful.

Collapse
tomekbuszewski profile image
Tomek Buszewski

Super, it makes it really clear now ;)