我具有以下格式的传感器数据:
zdata =
{ "data": [
{
"timestamp": 10,
"sensor_id": 1,
"temp": 14.5,
"hum":13,
"light":11,
},
{
"timestamp": 20,
"sensor_id": 1,
"temp": 18,
"hum":12,
"light":20,
},
{
"timestamp": 5,
"sensor_id": 2,
"temp": 24.5,
"hum":12,
"light":15,
},
{
"timestamp": 20,
"sensor_id": 2,
"temp": 29.5,
"hum":12,
"light":2,
}
]
};
我使用Chart js显示传感器读数。我正在使用的数据来自两个不同的sensor_id(传感器1和传感器2),它们不一定具有相同的时间戳。每个传感器都会发送光线,湿度和温度的读数。我需要根据时间在图表上绘制两个传感器的读数,因此需要上面的数据像这样:
时间戳= [5、10、20]
传感器= [1,2]
tempValueArray = [['',14.5,18],[24.5,'',29.5]]
humidityValueArray = [['',13,18],[24.5,'',29.5]]
lightValueArray = [['',13,12],[12,'',12]]
最初,我只是使用带有时间图的温度传感器,并将代码发布为答案:Organising object data by timestep, so as to chart multiple sensor readings against time using Chart JS
但是,我已经更新了此处的代码,以遍历每种阅读类型(即温度,嗡嗡声,光线):
var sensorNames = ['temp','hum','light'];
var allSensors = [];
for (i = 0; i < sensorNames.length; i++) {
let {sensors ,...sensorTimeMap} = zdata.data.reduce((acc,val) => {
sensorTypes = [val.temp, val.hum, val.light];
if(!acc[val.timestamp]) acc[val.timestamp] = {};
acc[val.timestamp][val.sensor_id] = sensorTypes[i];
if(!acc.sensors.includes(val.sensor_id))
acc.sensors.push(val.sensor_id)
return acc;
},{sensors:[]}); // get available sensors and create a timeStamp map for future iterations
let timestamp = Object.keys(sensorTimeMap);
allSensors.push(sensors.map(sensor => (Object.values(sensorTimeMap).map(obj => obj[sensor] || ''))));
};
console.log(sensors);
console.log(allSensors);
有没有更有效的方法来执行此循环?我是javascript新手,因此不确定如何在地图中添加多个读数并将每个读数保存到新数组。