如何映射对象数组的数组中的属性- reactjs



如何通过对象数组中的数组中的属性进行映射?

澄清我的观点这里是我的代码结构,外部数组包含4个内部数组 -数字不应该是4 - 每个内部数组有一个我想要选择的属性标题。我想选择inner array中的所有标题属性并将其返回到单独的数组

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函数中使用内部数组的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'}
]
];
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);

一种可能性是首先将数组平铺成一个,然后使用map遍历它:

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

最新更新