以下是一个数据对象,我如何使用javascript遍历此对象,以便在每个唯一日期将一个“值”字段放入数组中?
我知道如何获取所有数据,但是我需要为每个唯一的日期获取一个(在这种情况下,时间可以忽略)
{
name: "test",
data: Array(200)
}
data: Array(200)
0: {
@id: "p23o"
code: "02"
dateTime: "2018-12-12T04:38:00Z"
value: -0.645
}
1: {
@id: "p453o"
code: "02"
dateTime: "2018-12-12T07:48:00Z"
value: -0.3645
}
2: {
@id: "p4423o"
code: "032"
dateTime: "2018-12-11T07:13:00Z"
value: -0.645
}
+ 198 more objects
该数组每天需要包含一个值数据。如何处理并将这些数据插入数组?最佳做法是什么?
谢谢!
答案 0 :(得分:1)
使用Date
将string
日期转换为Date
对象,然后创建没有时间的日期。
请遵循以下代码:
// data will be the variable containing your response
var uniqueData = {};
data.forEach(item => {
var date = new Date(item.dateTime);
var onlyDaysTime = new Date(date.getYear(), date.getMonth(),
date.getDate());
var key = onlyDaysTime.toString();
if(typeof uniqueData[key] === 'undefined') {
uniqueData[key] = [];
}
uniqueData[key].push(item);
})
for(key in uniqueData) {
console.log(uniqueData[key]);
}
输出:
[[object Object] {
code: "02",
dateTime: "2018-12-12T04:38:00Z",
id: "p23o",
value: -0.645
}, [object Object] {
code: "02",
dateTime: "2018-12-12T07:48:00Z",
id: "p453o",
value: -0.3645
}]
[[object Object] {
code: "032",
dateTime: "2018-12-11T07:13:00Z",
id: "p4423o",
value: -0.645
}]
答案 1 :(得分:0)
您可以使用array#reduce
将对应于每个唯一日期的对象存储在对象累加器中,然后使用Object.values()
从该对象获取所有值
let data = [{ "@id": "p23o", code: "02", dateTime: "2018-12-12T04:38:00Z", value: -0.645 } , { "@id": "p453o", code: "02", dateTime: "2018-12-12T07:48:00Z", value: -0.3645 } , { "@id": "p4423o", code: "032", dateTime: "2018-12-11T07:13:00Z", value: -0.645 }],
result = Object.values(data.reduce((r,o) => {
let date = o.dateTime.substring(0,10);
if(!(date in r)) r[date] = {...o};
return r;
},{}));
console.log(result);