简体   繁体   English

使用 map 或 reduce 将数组转换为记录

[英]convert array to record with map or reduce

I have this 2d array.我有这个二维数组。

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

I would like to know how to convert it to record with reduce or map:我想知道如何使用 reduce 或 map 将其转换为记录:

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

I want to use it to know in each row how col is longest.我想用它来知道每一行的 col 最长。

thanks谢谢

You can easily use an array map that loops through each item in the array and parses it.您可以轻松地使用数组映射来循环遍历数组中的每个项目并对其进行解析。

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 }
    ]
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM