使用地图或减少将数组转换为记录



我有这个 2d 数组。

[["hair",4560],["ringtones",33]]

我想知道如何将其转换为使用reduce或map进行记录:  

[{id: {product:"hair"}, price: [454]}, {id: {product:"ringtones"}, price: [6000]}] 

我想用它来了解每一行的 col 最长。

谢谢

您可以轻松使用数组映射来循环遍历数组中的每个项目并对其进行解析。

let array = [["hair",4560],["ringtones",33]];
let arrayOfObjects = array.map(e => {
// The structure as recommended in the comments
// If you want the nested structure you originally were wondering about,
// you can change the return line to match that structure
return {product: e[0], price: e[1]};
});
/**
Contents of the arrayOfObjects is:
[
{ product: 'hair', price: 4560 },
{ product: 'ringtones', price: 33 }
]
*/

最新更新