[英]map a 3 nested array javascript
const aboutMe = [{ "name": "frank", "about": [{ "mood": "happy", "dinner": [{ "first": "desert", "last": "noodles" }] }, { "mood": "happy", "dinner": [{ "first": "desert", "last": "noodles" }] }, { "mood": "happy", "dinner": [] } ] }] const AllBreak = aboutMe.about.map((dinner) => ((dinner.first, dinner.last))); const expectedOutput =["first": "desert", "last": "noodles", "first": "desert", "last": "noodles"] console.log(aboutMe, AllBreak, expectedOutput)
所以我试图通过从教程中学习的嵌套数组进行过滤
首先, aboutMe
是一个包含 object 的数组,其中包含about
属性。 所以,如果你想访问这个属性,你需要先访问数组的第一个元素,然后访问其中的about
属性。
其次, (dinner.first, dinner.second)
在这里实际上没有任何意义。 因为当括号中有多个用逗号分隔的表达式时,每个表达式都会被计算,但只返回最后一个。 所以,这里返回(dinner.first, dinner.second)
等价于返回dinner.second
。
所以,如果你只想要dinner.second
,那么只需返回它或将它们放入一个数组(或对象)中并返回它。
此外,由于在您的示例中,似乎不能保证dinner
数组中始终包含 object,因此最好在此处使用可选链接。
请看下面的解决方案:
const aboutMe = [{name:"frank",about:[{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[]}]}], res = aboutMe[0].about.map(({dinner}) => [dinner?.[0]?.first, dinner?.[0]?.last]) console.log(res);
aboutMe
是一个数组,如果要获取第一个元素的属性,可以使用索引[0]
const AllBreak = aboutMe[0].about.map(() => ...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.