+ 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
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;
+ 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?
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