简体   繁体   中英

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)

so am trying to filter through a nested array learning from a tutorial I don't know why it returns cannot read property of map why is that pretty sure i filtered correctly according to the tutorial

  • Firstly, aboutMe is an array with an object that has an about property in it. So, if you want to access this property, you need to first access the first element of the array and then access the about property in it.

  • Secondly, (dinner.first, dinner.second) doesn't actually make any sense here. Because when you have multiple expressions separated by commas in a bracket, each of those expressions get evaluated but only the last one is returned. So, here returning (dinner.first, dinner.second) is equivalent to returning dinner.second .

  • So, if you only want dinner.second then just return that or put them in an array (or object) and return that.

  • Also, since in your example it seems that it is not guaranteed that the dinner array would always have an object inside it, it is best to use Optional Chaining here.

Please have look at the solution below:

 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 is an array, if you want to get the property of the first element, you can use indexing [0]

const AllBreak = aboutMe[0].about.map(() => ...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM