簡體   English   中英

如何通過對象數組 arrays 中的屬性 map - reactjs

[英]how to map through a property inside an array of arrays of objects - reactjs

我如何通過 arrays 對象數組中的屬性來 map?

在這里澄清我的觀點是我的代碼結構,外部數組包含 4 個內部 arrays - 數字不應該是四個 -每個內部數組都有一個我想要選擇的屬性標題。 我想選擇內部數組中的所有傾斜屬性並將其返回到單獨的數組中

Array(4)
0: Array(1)
0: {_id: 'Mc-mi_000000001', title: 'McRoyale', section: {…}, imageSrc: 'McRoyal.png', price: 70, …}
length: 1
[[Prototype]]: Array(0)
1: Array(2)
0: {_id: 'Mc-mi_000000002', title: 'Big Mac', section: {…}, imageSrc: 'Bigmac.png', price: 55, …}
1: {_id: 'Mc-mi_000000003', title: 'Big Tasty', section: {…}, imageSrc: 'Big-tasty-Beef.png', price: 75, …}
length: 2
[[Prototype]]: Array(0)
2: Array(3)
0: {_id: 'Mc-mi_000000022', title: 'McNuggets 6 Pieces', section: {…}, imageSrc: 'McNuggets-6psc.png', price: 50, …}
1: {_id: 'Mc-mi_000000030', title: 'McFries', section: {…}, imageSrc: 'Large-Frise.png', price: 30, …}
2: {_id: 'Mc-mi_000000039', title: 'American Coffee', section: {…}, imageSrc: 'Ame-R-700x474.png', price: 25, …}
length: 3
[[Prototype]]: Array(0)
3: Array(1)
0: {_id: 'Mc-mi_000000041', title: 'Happy Meal Cheeseburger', section: {…}, imageSrc: 'HM-D-Chesseburger.png', price: 35, …}
length: 1
[[Prototype]]: Array(0)
length: 4
[[Prototype]]: Array(0)

如何將每個內部數組中的 title 屬性放入單獨的數組中?

如果要保留嵌套數組結構,可以在外部/主數組的 map function 內的內部 arrays 上使用 map function。

 const data = [ [ {_id: 'Mc-mi_000000001', title: 'McRoyale'} ], [ {_id: 'Mc-mi_000000002', title: 'Big Mac'}, {_id: 'Mc-mi_000000003', title: 'Big Tasty'} ], [ {_id: 'Mc-mi_000000022', title: 'McNuggets 6 Pieces'}, {_id: 'Mc-mi_000000030', title: 'McFries'}, {_id: 'Mc-mi_000000039', title: 'American Coffee'} ] ]; const titleData = data.map(innerArray => innerArray.map(({title}) => title)); console.log(titleData); /*Expected results: [ [ "McRoyale" ], [ "Big Mac", "Big Tasty" ], [ "McNuggets 6 Pieces", "McFries", "American Coffee" ] ] */

您可以通過嵌套調用.map來收集這些標題:

 const data = [[{_id: 'Mc-mi_000000001', title: 'McRoyale' }], [{_id: 'Mc-mi_000000002', title: 'Big Mac'},{_id: 'Mc-mi_000000003', title: 'Big Tasty'}], [{_id: 'Mc-mi_000000022', title: 'McNuggets 6 Pieces' },{_id: 'Mc-mi_000000030', title: 'McFries' },{_id: 'Mc-mi_000000039', title: 'American Coffee'}], [{_id: 'Mc-mi_000000041', title: 'Happy Meal Cheeseburger' }]]; const titles = data.map(arr => arr.map(({title}) => title)); console.log(titles);

一種可能性是首先將您的 arrays 扁平化為一個然后 go 通過它與 map:

[[{title: "a"}, {title: "b"}], [{title: "c"}]].reduce((acc, arr) => ([...acc, ...arr]), []).map(obj => obj.title)

暫無
暫無

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

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