JSON编码字符串的数据处理

时间:2019-06-21 19:03:42

标签: javascript json data-manipulation

我有以下JSON编码的字符串,我希望使用javascript进行操作,以便将x和y轴值组合成二维数组名称值。

MATCH (user)-[:PROFILE]->()-[:DATES]->(dates:Dates) 
WHERE '2019-10-19T18:29:04.116Z' < dates.endDate < '2020-06-20T18:29:04.116Z'
RETURN user 
ORDER BY dates.endDate ASC

我需要渲染为:

[
  {
    "key": "0",
    "xaxis": "1492041600000",
    "yaxis": "512"
  },
  {
    "key": "0",
    "xaxis": "1492045200000",
    "yaxis": "985"
  },
  {
    "key": "1",
    "xaxis": "1492048800000",
    "yaxis": "685"
  },
  {
    "key": "1",
    "xaxis": "1492052400000",
    "yaxis": "935"
  }
]

有人可以告诉我如何执行此数据操作吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用map-reduce,您应该能够获得想要的行为。

const results = [{"key":"0","xaxis":"1492041600000","yaxis":"512"},{"key":"0","xaxis":"1492045200000","yaxis":"985"},{"key":"1","xaxis":"1492048800000","yaxis":"685"},{"key":"1","xaxis":"1492052400000","yaxis":"935"}]


const reducedResults = results.reduce((acc, result) => {
  if(acc[result.key]) {
    acc[result.key].values.push([result.xaxis, result.yaxis]);
  } else {
    acc[result.key] = { key: result.key, values: [[result.xaxis, result.yaxis]] }
  }
  
  return acc;
}, {});

const newResults = Object.values(reducedResults);

console.log(newResults);