汇总表中的JSON

时间:2019-07-14 10:11:15

标签: json datatable summary

我有像这样的小型JSON:

let testJson = [
  {"date":"2019.05.21","name":"Péter","num":"8"}, 
  {"date":"2019.05.22","name":"Norbert","num":"6"}, 
  {"date":"2019.05.21","name":"Sándor","num":"7"}, 
  {"date":"2019.05.24","name":"Béla","num":"4"},    
  {"date":"2019.05.23","name":"Sándor","num":"5"},  
  {"date":"2019.05.26","name":"Sándor","num":"6"},  
  {"date":"2019.05.27","name":"Péter","num":"7"},  
  {"date":"2019.05.28","name":"Péter","num":"8"}, 
  {"date":"2019.05.29","name":"Péter","num":"3"}, 
  {"date":"2019.05.30","name":"Péter","num":"6"}, 
  {"date":"2019.05.31","name":"Péter","num":"4"}
];

我想这样汇总数据:

enter image description here

2 个答案:

答案 0 :(得分:2)

尝试一下:

let testJson = [
  {"date":"2019.05.21","name":"Péter","num":"8"}, 
  {"date":"2019.05.22","name":"Norbert","num":"6"}, 
  {"date":"2019.05.21","name":"Sándor","num":"7"}, 
  {"date":"2019.05.24","name":"Béla","num":"4"},    
  {"date":"2019.05.23","name":"Sándor","num":"5"},  
  {"date":"2019.05.26","name":"Sándor","num":"6"},  
  {"date":"2019.05.27","name":"Péter","num":"7"},  
  {"date":"2019.05.28","name":"Péter","num":"8"}, 
  {"date":"2019.05.29","name":"Péter","num":"3"}, 
  {"date":"2019.05.30","name":"Péter","num":"6"}, 
  {"date":"2019.05.31","name":"Péter","num":"4"}
];
const groupBy = (arr) => arr.reduce((acc, ele)=>( (acc[ele.date] = acc[ele.date] || []).push(ele), acc),{})
const reformat = ([k, v])=> ({date:k,...Object.assign({},...v.map(l=>({[l.name]:l.num})))})
const result = Object.entries(groupBy(testJson))
.map(ele=>reformat(ele));

console.log(result);

答案 1 :(得分:0)

example json format格式的其他解决方案:

let testJson = [
  {"date":"2019.05.21","name":"Péter","num":"8"}, 
  {"date":"2019.05.22","name":"Norbert","num":"6"}, 
  {"date":"2019.05.21","name":"Sándor","num":"7"}, 
  {"date":"2019.05.24","name":"Béla","num":"4"},    
  {"date":"2019.05.23","name":"Sándor","num":"5"},  
  {"date":"2019.05.26","name":"Sándor","num":"6"},  
  {"date":"2019.05.27","name":"Péter","num":"7"},  
  {"date":"2019.05.28","name":"Péter","num":"8"}, 
  {"date":"2019.05.29","name":"Péter","num":"3"}, 
  {"date":"2019.05.30","name":"Péter","num":"6"}, 
  {"date":"2019.05.31","name":"Péter","num":"4"}
];
const groupBy = (arr) => arr.reduce((acc, ele)=>( (acc[ele.date] = acc[ele.date] || []).push(ele), acc),{})
const reformat = ([k, v])=> ({[k]:v.map((res,i)=>({id:i, name:res.name, datum:res.date, number:res.num}))})
const result = Object.entries(groupBy(testJson))
.map(ele=>reformat(ele));

console.log(result);