Reputation: 1429
I have the following object:
const john = {
family: [
{ firstName: 'david', secondName: 'jana' },
{ firstName: 'eyal', secondName: 'shani ' },
],
};
I want to get 'david' string in one operation. So i tried the following code:
const { family:[0]{firstName}}} = john;
But i'm getting the error :
"Destructuring expressions can only have identifier references"
Can someone tell me in simple words (cause i'm new in the language) what i'm doing wrong?
Upvotes: 0
Views: 116
Reputation: 370679
To extract a deeply nested value with destructuring, the syntax is nearly identical to when declaring an object with those properties. family:[0]
isn't valid syntax - instead, you need to surround the contents of family
in array delimiters:
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { family:[{firstName}]} = john;
console.log(firstName);
But I'd highly recommend against using nested destructuring like this. It's so hard to write and read and understand. Better to use plain dot notation at least for the outer accesses, eg
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { firstName } = john.family[0];
console.log(firstName);
Upvotes: 3