簡體   English   中英

如何將一組對象分組到新數組中?

[英]How can I group an array of objects in new array?

我有以下數組


    const arr = [
      {
       Images: [{ id: 1 }, { id: 2 }, { id: 3 }],
       MediaCategoryName: "Exterior",
       id: 51
      },

       {
       Images: [{ id: 7 }, { id: 8 }, { id: 9 }],
       MediaCategoryName: "Construction",
       id: 687
      },

      {
      Images: [{ id: 10 }, { id: 11 }, { id: 21 }],
      MediaCategoryName: "home",
      id: 755
     }
    ];

如何從它們創建新數組並僅放置Images

我需要這樣的東西

newArr = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 7 }, { id: 8 }
         , { id: 9 }, { id: 10 }, { id: 11 }, { id: 21 }
         ]

有人可以幫助我實現這一目標嗎?

謝謝 :)

使用Array.prototype.flatMap()
這就像做一個地圖來返回圖像,然后再執行一個平面

 const arr = [ { Images: [{ id: 1}, {id: 2}, {id: 3 }] , MediaCategoryName: 'Exterior', id: 51 } , { Images: [{ id: 7}, {id: 8}, {id: 9 }] , MediaCategoryName: 'Construction', id: 687 } , { Images: [{ id: 10}, {id: 11}, {id: 21 }] , MediaCategoryName: 'home', id: 755 } ]; const res = arr.flatMap(({Images}) => Images) console.log(JSON.stringify(res))
 .as-console-wrapper {max-height: 100% !important;top: 0;} .as-console-row::after {display: none !important;}

你可以試試這段代碼。 它將從arr中獲取每個元素並獲取

out = []
arr.forEach((el)=>{
    x.push(...el.Images)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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