javascript - 使用angular请求的数据需要根据时间分块渲染到页面的上,求思路?
问题描述
$scope.data=[ {'time':'2017/06/23','money':'3000','type':'RMB'}, {'time':'2017/06/24','money':'4000','type':'RMB'}, {'time':'2017/07/23','money':'3000','type':'RMB'}, {'time':'2017/07/24','money':'4000','type':'RMB'}, {'time':'2017/07/25','money':'5000','type':'RMB'} ];
请求到的数据类似这样,要根据time字段的时间,根据月份显示数据,怎样把六月和七月的数据过滤开比如渲染到页面要这样显示 :6月23号 金额:3000 类别:人民币24号 金额:4000 类别:人民币7月23号 金额:3000 类别:人民币24号 金额:4000 类别:人民币25号 金额:5000 类别:人民币
问题解答
回答1:最终把数据格式转换成:
newData = [ {time: ’2017/06’,items: [ { time: ’2017/06/23’, money: ’3000’, type: ’RMB’}, { time: ’2017/06/24’, money: ’4000’, type: ’RMB’},] }, {time: ’2017/07’,items: [ { time: ’2017/07/23’, money: ’3000’, type: ’RMB’}, { time: ’2017/07/24’, money: ’4000’, type: ’RMB’},] }, ];
然后使用两个ng-repeat渲染。
至于思路的话:
先转换成一个对象:
obj = {
’2016/06’: [ { time: ’2017/06/23’, money: ’3000’, type: ’RMB’}, { time: ’2017/06/24’, money: ’4000’, type: ’RMB’},],’2016/07’: [ { time: ’2017/07/23’, money: ’3000’, type: ’RMB’}, { time: ’2017/07/24’, money: ’4000’, type: ’RMB’},]
}
然后遍历对象,转换成数组。
const data = [ { time: ’2016/06/23’, money: ’1000’, type: ’RMB’ }, { time: ’2016/06/24’, money: ’1200’, type: ’RMB’ }, { time: ’2016/07/12’, money: ’1200’, type: ’RMB’ }, { time: ’2016/07/15’, money: ’1200’, type: ’RMB’ }, ]; const obj = _.groupBy(data, item => item.time.substr(0, 7)); // 我这里使用了lodash,自行遍历数组也是一样的 const newData = Object.keys(obj).map(time => ({ time, items: obj[time] })); console.log(newData, 2);回答2:
虽然可以利用数组过滤匹配等对time进行拆分成你想要的格式,但是考虑到效率问题,我建议这些在服务端进行处理,返回你想要的数据格式,实在没办法的话再考虑数据分类处理
