【问题标题】:Merge an array with a 2d array to an array of objects, with the keys are the elements of the 1d array将带有二维数组的数组合并到对象数组中,键是一维数组的元素
【发布时间】:2022-01-12 05:29:28
【问题描述】:

我有 2 个这样的数组

const dates = ["2019", "2020", "2021"];
const data = [[100, 200, 300, 20], [400, 500, 600, 30], [700, 800, 900, 40]];

我想将这 2 个数组合并成这样的对象数组 细节: 结果数组的第一个对象将具有二维数组中每个数组的第一个元素的值 其余的结果数组也是如此

const result = [
 {
  2019: 100,
  2020: 400,
  2021: 700
 },
 {
  2019: 200,
  2020: 500,
  2021: 800
 },
 {
  2019: 300,
  2020: 600,
  2021: 900
 },
 {
  2019: 20,
  2020: 30,
  2021: 40
 }
]

【问题讨论】:

  • 内部二维数组中有 4 个值,对象有 3 个值。那么你想用多余的来做什么呢?
  • @code 基本上结果数组用于条形图,每个对象将是一组。所以第一个对象将是一组 3 个条形图。希望这是有道理的,对不起我的英语不是那么好

标签: javascript arrays object


【解决方案1】:

我会建议你首先 transpose 你的 data 行然后你可以写 table 使用 Array.prototype.mapObject.fromEntries -

const transpose = t =>
  t.some(a => Boolean(a.length))
    ? [t.map(a => a[0]), ...transpose(t.map(a => a.slice(1)))]
    : []
    
const table = (columns, rows) =>
  transpose(rows).map(r =>
    Object.fromEntries(columns.map((c,i) =>
      [c, r[i]]
    ))
  )

const dates = ["2019", "2020", "2021"]
const data = [[100, 200, 300, 20], [400, 500, 600, 30], [700, 800, 900, 40]]

console.log(table(dates, data))

【讨论】:

  • 不错,但是结果缺少二维数组内部数组的最后一个元素
  • @Lucas 我会首先推荐你transpose 数据行。详情见我的更新
【解决方案2】:

也许你可以试试这个:

const dates = ["2019", "2020", "2021"];
const data = [[100, 200, 300, 20], [400, 500, 600, 30], [700, 800, 900, 40]];

const res=data[0].reduce((a,_,j,da)=>{
  a.push(Object.fromEntries(dates.map((d,i)=>[d,data[i][j]])))
  return a;
},[]);

console.log(res)

【讨论】:

  • 不错,但是结果缺少二维数组内部数组的最后一个元素
  • 请再次检查,我编辑了我的代码。
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-09
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多