简体   繁体   English

我正在尝试使用解构赋值提取 object 的值,年龄变量表示未定义。 我做错了什么?

[英]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.

相关问题 尝试增加数字变量时的角度“此未定义”,不确定我在做什么 - Angular “this is undefined” when trying to increment number variable, not sure what I'm doing wrong Discord.js - 类型错误:无法读取未定义的属性“声音”。 有人可以告诉我我做错了什么吗? - Discord.js - TypeError: Cannot read property 'voice' of undefined. Can someone tell me what I'm doing wrong? 我正在尝试通过输入生日来输出年龄的函数。 我没有从中得到输出。 我做错了什么? - I'm trying to make a function that outputs age by entering birthdate. I'm not getting an output from this. What I'm I doing wrong? 尝试设置Cookie,但显示未定义。 我该怎么办? - Trying to set cookie, but it says undefined. What do i do? 尝试回叫功能时我做错了 - What I'm doing wrong when trying call back function 我正在使用iron:router v1.0.7,但是this.render()是“ undefined”。 我看不到我在做什么 - I'm using iron:router v1.0.7 but this.render() is “undefined”. I can't see what I'm doing wrong Javascript 说对象值未定义。 我究竟做错了什么? - Javascript saying object value is undefined. What am I doing wrong? AngularJS-我在注射中做错什么? - Angularjs - what I'm doing wrong with injections? 我正在尝试使用javascript中的对象分解来打印名字和姓氏,但它给forEaach函数提供了错误 - I'm trying to print the first and last name using object destructuring in javascript but it gives an error for the forEaach function 我正在尝试使用 Google Scripts 为电子表格的每一新行发布一条 Slack 消息 - 但我只收到一个帖子。 我究竟做错了什么? - I'm trying to post a Slack message for each new row of a spreadsheet using Google Scripts - but I'm only getting one post. What am I doing wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM