【问题标题】:How to convert a javascript array of Objects from one format to another format?如何将对象的 javascript 数组从一种格式转换为另一种格式?
【发布时间】:2021-06-20 20:04:33
【问题描述】:

我有一个对象数组,想将其从一种格式转换为另一种格式。

初始数组如下所示:

  const data = [
    {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}},
    {name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}},
    {name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}}
  ]

如何转换成这样的格式?

  const data = [
    {channel: 'Oil', 'Customer 1':  55, 'Customer 2': 59, 'Customer 3': 50},
    {channel: 'Gas', 'Customer 1':  66, 'Customer 2': 96, 'Customer 3': 69},
    {channel: 'Retail', 'Customer 1':  56, 'Customer 2': 86, 'Customer 3': 50},
    
  ]

请帮忙?

【问题讨论】:

标签: javascript arrays json reactjs object


【解决方案1】:

您可以填充关闭值类别的对象并添加相关数据。

  const data = [
    {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}},
    {name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}},
    {name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}}
  ]

const output = Object.values(data.reduce((a, c) => {
  Object.keys(c.value).forEach(k => {
    a[k] = a[k] || {channel: k};
    a[k][c.name] = c.value[k];
  });
  return a;
}, {}));

console.log(output);

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多