Javascript 本机重新格式化JSON对象,为JS图做好准备

Javascript 本机重新格式化JSON对象,为JS图做好准备,javascript,json,Javascript,Json,我正在使用的当前JSON: [ { "price": 498, "source": "example", "timestamp": 1569700356 }, { "price": 499, "source": "example", "timestamp": 1569700357 }, { "price": 479, "source": "example2", "timestamp": 156970035

我正在使用的当前JSON:

[
  {
    "price": 498,
    "source": "example",
    "timestamp": 1569700356
  },
  {
    "price": 499,
    "source": "example",
    "timestamp": 1569700357
  },
  {
    "price": 479,
    "source": "example2",
    "timestamp": 1569700358
  },
  {
    "price": 498,
    "source": "example2",
    "timestamp": 1569786756
  }
]
预期结果:

     [{
          name: 'example',
          data: [
            [1569700356, 498],
            [1569700357, 499]
          ]
        },
        {
          name: 'example2',
          data: [
            [1569700358, 479],
            [1569786756, 498]
          ]
        }
      ]
以上解释:上述预期结果将是我正确绘制价格数据所需的本机JSON输入。源
示例
示例2
[时间戳,价格]
组合在源下的列表中

我的要求/我目前的方法:我想要一个优雅的解决方案,我已经尝试了数据地图,并尝试按不同的方式进行分组。。。如果可能的话,我不想导致大量的for循环和if语句。

const数组=[
{
“价格”:498,
“来源”:“示例”,
“时间戳”:1569700356
},
{
“价格”:499,
“来源”:“示例”,
“时间戳”:1569700357
},
{
“价格”:479,
“来源”:“示例2”,
“时间戳”:1569700358
},
{
“价格”:498,
“来源”:“示例2”,
“时间戳”:1569786756
}
];
const res=数组。reduce((acc,curr)=>{
if(根据[当前来源]){
acc[curr.source].data.push([curr.timestamp,curr.price]);
}否则{
会计科目[当前来源]={
名称:curr.source,
数据:[[curr.timestamp,curr.price]]
};
}
返回acc;
}, {});

console.log(Object.values(res))您可以使用实用程序功能来处理数据。它使用映射对具有相同源的项目进行分组

function processData(data) {
  const unique = new Map();

  data.forEach(item => {
    const { source, price, timestamp } = item;
    if (unique.has(source)) {
      unique.get(source).data.push([price, timestamp]);
    } else {
      unique.set(source, { name: source, data: [[price, timestamp]]});
    }
  });

  return [...unique.values()];
}

预期的尝试在哪里?这似乎比.map处理得好得多,name未定义,使用
name:curr.name
->
name:curr.source
修复。但是,结果接近,但与预期不符。我想这已经是我现在可以完成的一个方向了。如果/当我得到最终预期结果时,我将更新。谢谢很好,我将
[[price,timestamp]]
切换到
[[timestamp,price]]]
,它与预期的输出相匹配。谢谢Abito