【问题标题】:Data Manipulation of json encoded string [duplicate]json编码字符串的数据操作[重复]
【发布时间】:2019-06-21 19:03:42
【问题描述】:

我有以下 JSON 编码字符串,我想使用 javascript 来操作它,以便将 x 和 y 轴值组合成一个二维数组名称值。

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

我需要渲染为:

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

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

谢谢!

【问题讨论】:

    标签: javascript json data-manipulation


    【解决方案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);

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多