【问题标题】:convert array to record with map or reduce使用 map 或 reduce 将数组转换为记录
【发布时间】:2020-03-21 05:19:29
【问题描述】:

我有这个二维数组。

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

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

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

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

谢谢

【问题讨论】:

  • 这个问题有几个问题,特别是你没有提供真正的尝试或努力来解决这个问题,但我质疑预期的结果......id一个对象我>? (product?)price 是一个只有一个值的数组吗?这一切似乎有点奇怪。
  • 您确定需要记录中的所有嵌套数组和对象吗?为什么不把它做成一个对象数组呢?
  • its better to access item like id.product, access.price. Its 用数组做起来不容易
  • 用这种形式输出不是更有意义吗?:[{product: 'hair', price: 454}, {product: 'ringtones', price: 6000}]

标签: javascript arrays dictionary record reduce


【解决方案1】:

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

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

【讨论】:

  • 谢谢 Daniel_I_Am
猜你喜欢
  • 2021-07-08
  • 1970-01-01
  • 2021-12-27
  • 2018-12-26
  • 2018-08-17
  • 1970-01-01
  • 2017-12-24
  • 2019-04-11
  • 2023-03-14
相关资源
最近更新 更多