+ 5

How does object destructuring work?

let obj = {prop1: tomato, prop1: apple}; let { prop1, prop2 } = obj; console.log(prop1); //output: tomato didnt understand a thing

22nd Aug 2018, 7:39 PM
Brian Gonzalez
Brian Gonzalez - avatar
3 Answers
+ 8
There are some errors in your snippet in the first line, the prop1 key is there twice and tomato and apple are missing the quotation marks šŸ˜… Here's the code fixed: let obj = {prop1: 'tomato', prop2: 'apple'}; let {prop1, prop2} = obj; console.log(prop1); Now, regarding your question, object destructuring allows you to create a variable and assign it a value, in a single line of code. If we take a look at line 2, we are creating two variables, the first one is called prop1 and the second one is called prop2, in this case they match the name of the keys of the object. Basically this: let { prop1, prop2 } = obj; Is the equivalent of: let prop1 = obj.prop1; let prop2 = obj.prop2;
23rd Aug 2018, 2:11 AM
Pao
Pao - avatar
+ 1
Pao let obj = {prop1: "tomato", prop2: "apple"}; 1: let { prop1, prop2 } = obj; 2: let prop1 = obj.prop1; let prop2 = obj.prop2; ------- I'm afraid (1) and (2) are not quite the same. In (2) you can use any variable names. In (1) if you try to use variable names other than the ones used in the object, it will give an error. But why? How it works?
19th Jan 2019, 12:35 PM
ŠœŠ°ŠŗсŠøŠ¼ ŠœŠ°Ń‚Ń€ŠµŠ½ŠøцŠŗŠøŠ¹
ŠœŠ°ŠŗсŠøŠ¼ ŠœŠ°Ń‚Ń€ŠµŠ½ŠøцŠŗŠøŠ¹ - avatar
0
let obj = {prop1 : tomato, prop2 : apple}; let {testvar1 , testvar2} = obj; console.log(testvar1) I encourage you to try the code for the answer of the output and to revisit the fourth example
24th Jan 2019, 8:16 PM
Tomas Bartninkas
Tomas Bartninkas - avatar