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.
const object = {price: 42, qId: true};
const {price, qId} = object;
console.log(price); // 42
console.log(qId); // true
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"
If you have any destructuring 🧰 tips, share them below.
Top comments (3)
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.
@tomekbuszewski thanks for the tip. I've renamed the variables to be more meaningful.
Super, it makes it really clear now ;)