如何将json结构从简单转换为复杂?

时间:2018-02-23 13:33:36

标签: javascript arrays json time-series

我将这种简单的数据结构应用于复杂的结构:

{"item" :  "Light",
"value":  39,
"time" :  151869596954},

{"item" :  "Bat",
"value":  3.412,
"time" :  1518695969954},

{"item" :  "Humidity",
"value":  56,
"time" :  1518697292308},

{"item" : "InternalTemperature",
"value": 22.2,
"time" : 1518697292308}]

我试图将其转换为使用javascript:

[
  {
    time: 1518697292308,
    InternalTemperature : 22,
    Humidity : 33,
    Bat : 9
  }
]

1 个答案:

答案 0 :(得分:-4)

您可以通过reduce function

轻松完成



const result = [{"item" :  "Light",
        "value":  39,
        "time" :  1518695969954},
    
        {"item" :  "Bat",
            "value":  3.412,
            "time" :  1518695969954},
    
        {"item" :  "Humidity",
            "value":  56,
            "time" :  1518697292308},
    
        {"item" : "InternalTemperature",
            "value": 22.2,
            "time" : 1518697292308}].reduce(function(carry, item) {
        carry[0][item['item']] = item['value'];
        carry[0]['time'] = item['time'];
        return carry;
    }, [{}])
    
  document.write(JSON.stringify(result));