簡體   English   中英

map 一個 3 嵌套數組 javascript

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM