Reputation: 994
My code:
const users = [ { id: 1, name: 'user1' }, { id: 2, name: 'user2' } ]
p = new Promise( resolve => resolve(users) )
p.then( (user) => console.log(user) )
Return me the following logs:
[ { id: 1, name: 'user1' }, { id: 2, name: 'user2' } ]
If I change it as below,
users.then( ([user]) => console.log(user) )
I receive the following logs:
{ id: 1, name: 'user1' }
I don't quite understand why the second one only logs the first element in the array.
Upvotes: 2
Views: 50
Reputation: 23495
Destructuring is an ES6 aka ECMA2015 features.
You can destructure Array
and Objects
.
Object
destructuring as bellow, allow you to pick up the keys
you want to get from an object
using easy syntax.
const obj = {
a: 'a',
b: 'b',
c: 'c',
};
// Without object destructuring
const a_ = obj.a;
const b_ = obj.b;
// With object destructuring
const {
a,
b,
} = obj;
console.log(a);
Array
destructuring is quite the same, but instead of specifying the keys
you want to get, you use the index
of the data.
const arr = [
'a',
'b',
'c',
];
// Without array destructuring
const a_ = arr[0];
const c_ = arr[2];
// With array destructuring
const [
a, , c,
] = arr;
console.log(c);
You can use Array
and Object
destructuring anywhere; including in function parameters. It's especially good in this case because you can assign default
value easily to keys
, as bellow
function func({
a,
b,
c = 'default',
}) {
console.log(a, '/', b, '/', c);
}
func({
a: 'j\'aime la france',
b: 'vive les baguettes',
});
Upvotes: 0
Reputation: 4250
It's a destructuring assignment
[a, b, c] = [1, 2, 3]
console.log(a)
console.log(b)
console.log(c)
but if you only destructure one, you get the first value of the array
[a] = [1, 2, 3]
console.log(a)
As for your example, destructuring can be done in many places such as function arguments
Upvotes: 4