[英]I'm trying to extract the values of an object using destructuring assignment, the age variable says undefined. What I'm doing wrong?
const obj = { firstUser: { name: { firstName: 'John', lastName: 'Doe', }, age: 32, } } const { firstUser: { name: { lastName: Lname } }, age } = obj; console.log(Lname); console.log(age);
Try this way:试试这样:
const { firstUser } = obj;
const { name, age } = firstUser;
const { lastName: Lname } = name; // this is destructuring assignment
Now you can use lastName as Lname variable.现在您可以使用 lastName 作为 Lname 变量。
Because you have placed the age field inside firstName object,nested inside the obj.因为您已将年龄字段放在 firstName object 中,嵌套在 obj 中。 I have refactored your code
我重构了你的代码
const obj = { firstUser: { name: { firstName: 'John', lastName: 'Doe', }, }, age: 32, } const {firstUser:{name: {lastName: Lname}}, age} = obj; console.log(Lname); console.log(age);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.