转换数组以使用map或reduce记录

时间:2019-11-25 20:50:44

标签: javascript arrays dictionary record reduce

我有这个二维数组。

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

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

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

我想用它来知道每一行的col最长。

谢谢

1 个答案:

答案 0 :(得分:0)

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

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