我有点迷失,我有一个json格式的数据集,时间戳和ID如下:
[{
"date":"2016-11-18 19:20:42","id_pa":"7"
},{
"date":"2016-11-18 19:04:55","id_pa":"5"
},{
"date":"2016-11-19 20:53:42","id_pa":"7"
},{
"date":"2016-11-19 20:53:43","id_pa":"7"
},{
"date":"2016-11-19 20:53:43","id_pa":"7"
},{
"date":"2016-11-20 20:49:42","id_pa":"7"
},{
"date":"2016-11-20 20:50:45","id_pa":"7"
},{
"date":"2016-11-20 20:50:46","id_pa":"7"
}]
我想构建一个每天显示日期和ID数量的json。新的Json会是这样的:
[{
"date":"18-11-2016","num_pa":"2"
},{
"date":"19-11-2016","num_pa":"1"
},{
"date":"20-11-2016","num_pa":"1"
}]
我认为我必须使用 .map 格式化日期,以便显示dd-mm-yyyy,然后使用 .filter 删除重复项,最后删除< strong> .reduce 计算每个日期的不同ID。到目前为止,我只完成了.map程序,但我不确定如何进行后续步骤,我的解决方案是否是最佳解决方案。
这是我的一段代码:
SwapSvc
.getUsage (vm.id_fi)
.then((data)=>{
//console.log(`lreceived data: `+ JSON.stringify(data) );
vm.fdata = data.map((elem) => {
//console.log(`date: ${elem.date}`);
//console.log(`id_pa: ${elem.id_pa}`);
var d = new Date (elem.date);
return{
date:d.getDate()+'-'+d.getMonth()+'-'+d.getFullYear()/*elem.date*/,
id_pa:elem.id_pa
}})
var temp = [];
vm.filteredData = vm.fdata.filter((elem, index) => {
if(temp.indexOf(elem.date)<0){
temp.push(elem);
return true;
}
else return false;
});
console.log(`data after parsing and ordering: `+ JSON.stringify(vm.filteredData) );
return data;
})
.catch((err)=>{
//error
console.log(`error, no response`);
throw err;
});
PS:我正在使用角度1.6和ES6。 提前致谢 BRJ
答案 0 :(得分:0)
您可以使用哈希表作为日期,并收集所有id_pa
以便以后计算。
var data = [{ date: "2016-11-18 19:20:42", id_pa: "7" }, { date: "2016-11-18 19:04:55", id_pa: "5" }, { date: "2016-11-19 20:53:42", id_pa: "7" }, { date: "2016-11-19 20:53:43", id_pa: "7" }, { date: "2016-11-19 20:53:43", id_pa: "7" }, { date: "2016-11-20 20:49:42", id_pa: "7" }, { date: "2016-11-20 20:50:45", id_pa: "7" }, { date: "2016-11-20 20:50:46", id_pa: "7" }],
hash = Object.create(null),
result;
data.forEach(function (a) {
var date = a.date.slice(0, 10);
hash[date] = hash[date] || Object.create(null);
hash[date][a.id_pa] = true;
});
result = Object.keys(hash).map(date => ({ date, num_pa: Object.keys(hash[date]).length }));
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分:0)
您可以将reduce
链接到map
调用,并使用ES6 findIndex
方法查看当前对象是否存在于reduce
函数创建的数组中
SwapSvc
.getUsage (vm.id_fi)
.then((data)=>{
//console.log(`lreceived data: `+ JSON.stringify(data) );
vm.fdata = data.map((elem) => {
//console.log(`date: ${elem.date}`);
//console.log(`id_pa: ${elem.id_pa}`);
var d = new Date (elem.date);
return{
date:d.getDate()+'-'+d.getMonth()+'-'+d.getFullYear()/*elem.date*/,
id_pa:elem.id_pa
}}).reduce((p, c, i) => {
var index = p.findIndex(x => x.date === c.date);
if (index !== -1) p[index].num_pa++;
else p.push({"date": c.date, "num_pa": 1})
return p;
}, [])
console.log(`data after parsing and ordering: `+ JSON.stringify(vm.fData) );
return data;
})