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

convert array to record with map or reduce

我有这个二维数组。

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

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

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

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

谢谢

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

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