为什么在尝试破坏对象时得到 "Destructuring expressions can only have identifier references"?
Why getting "Destructuring expressions can only have identifier references" when trying to destruct an object?
我有以下 对象:
const john = {
family: [
{ firstName: 'david', secondName: 'jana' },
{ firstName: 'eyal', secondName: 'shani ' },
],
};
我想在一次操作中得到 'david' 字符串。所以我尝试了以下代码:
const { family:[0]{firstName}}} = john;
但我收到错误消息:
"Destructuring expressions can only have identifier references"
谁能用简单的语言告诉我(因为我是这门语言的新手)我做错了什么?
要通过解构提取深度嵌套的值,语法几乎与 声明具有这些属性的对象 相同。 family:[0]
不是有效语法 - 相反,您需要用数组定界符将 family
的内容括起来:
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { family:[{firstName}]} = john;
console.log(firstName);
但我强烈建议不要使用这样的嵌套解构。写作、阅读和理解是如此困难。至少对外部访问最好使用纯点符号,例如
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { firstName } = john.family[0];
console.log(firstName);
我有以下 对象:
const john = {
family: [
{ firstName: 'david', secondName: 'jana' },
{ firstName: 'eyal', secondName: 'shani ' },
],
};
我想在一次操作中得到 'david' 字符串。所以我尝试了以下代码:
const { family:[0]{firstName}}} = john;
但我收到错误消息:
"Destructuring expressions can only have identifier references"
谁能用简单的语言告诉我(因为我是这门语言的新手)我做错了什么?
要通过解构提取深度嵌套的值,语法几乎与 声明具有这些属性的对象 相同。 family:[0]
不是有效语法 - 相反,您需要用数组定界符将 family
的内容括起来:
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { family:[{firstName}]} = john;
console.log(firstName);
但我强烈建议不要使用这样的嵌套解构。写作、阅读和理解是如此困难。至少对外部访问最好使用纯点符号,例如
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { firstName } = john.family[0];
console.log(firstName);