从 json 中创建 javascript 中的字典列表

make a list of dictionnary in javascript from a json

我有一个字典列表,我从 API:

我可以通过这种方式获取数据 json :

[{"2020-03-11 14:00:00":10.765736766809729}
,{"2020-03-11 15:00:00":10.788090128755387},
{"2020-03-11 16:00:00":10.70594897472582},
{"2020-03-11 17:00:00":10.435443490700994},
{"2020-03-11 18:00:00":9.748152122079162},
{"2020-03-11 19:00:00":9.541845493562244},
{"2020-03-11 20:00:00":10.161242250834528}]

或者我也可以这样获取:

{"date":{"0":"2020-03-11 14:00:00","1":"2020-03-11 15:00:00","2":"2020-03-11 16:00:00","3":"2020-03-11 17:00:00","4":"2020-03-11 18:00:00","5":"2020-03-11 19:00:00","6":"2020-03-11 20:00:00","7":"2020-03-11 21:00:00","8":"2020-03-11 22:00:00","9":"2020-03-11 23:00:00","10":"2020-03-12 00:00:00"},
"availability":{"0":10.7657367668,"1":10.7880901288,"2":10.7059489747,"3":10.4354434907,"4":9.7481521221,"5":9.5418454936,"6":10.1612422508,"7":10.8490701001,"8":11.0297448736,"9":10.9386623748,"10":11.2957796853}}"

对于我的 React 应用程序中的胜利图表,我需要这样的列表:

[
{x : new Date("2020-03-11 14:00:00"),y: 10.765736766809729},
{x : new Date("2020-03-11 15:00:00"),y: 10.788090128755387},
{x : new Date("2020-03-11 16:00:00"),y: 10.70594897472582},
{x : new Date("2020-03-11 17:00:00"),y: 10.435443490700994},
{x : new Date("2020-03-11 18:00:00"),y: 9.748152122079162},
{x : new Date("2020-03-11 19:00:00"),y: 9.541845493562244},
{x : new Date("2020-03-11 20:00:00"),y: 10.161242250834528}
]

我是 javascript 的菜鸟。任何意见或建议将不胜感激。

您可以使用的转换代码如下。不过好像有点笨手笨脚了。

const arr = [
 {"2020-03-11 14:00:00":10.765736766809729},
 {"2020-03-11 15:00:00":10.788090128755387},
 {"2020-03-11 16:00:00":10.70594897472582},
 {"2020-03-11 17:00:00":10.435443490700994},
 {"2020-03-11 18:00:00":9.748152122079162},
 {"2020-03-11 19:00:00":9.541845493562244},
 {"2020-03-11 20:00:00":10.161242250834528},
 ];

const arr1 = arr.map((item) => {
  const convertedItem = JSON.stringify(item).replace(/[\{|\}]/g, '').split('":');
  const xDate = convertedItem.shift().replace(/"/g, '');
  const xPos = convertedItem.pop();

  return {
    x: new Date(xDate),
    y: xPos,
   };
});

您可以将数据映射到匹配您需要的结构的新对象。

const data = [
  {"2020-03-11 14:00:00":10.765736766809729},
  {"2020-03-11 15:00:00":10.788090128755387},
  {"2020-03-11 16:00:00":10.70594897472582},
  {"2020-03-11 17:00:00":10.435443490700994},
  {"2020-03-11 18:00:00":9.748152122079162},
  {"2020-03-11 19:00:00":9.541845493562244},
  {"2020-03-11 20:00:00":10.161242250834528}]
  
  var chartData = data.map(item => { 
    for (const key in item)
      return { x: new Date(key), y: item[key] }
  })`