前端处理后端返回数据
需求:将对象数组按照某一属性重新分组
// 原始数据 const items = [ { type: '1', title:'模块1' }, { type: '1', title:'模块2' }, { type: '2', title:'模块3' }, { type: '3', title:'模块4' }, { type: '3', title:'模块5' }, { type: '3', title:'模块6' }, ]初步思路:使用groupBy()方法
// 分组后的数据 ''内是作为分类依据的属性 typeItems = groupBy(items, 'type') // 分组后种类 typeKeys = Object.keys(typeItems)实现代码:
const sorted = (array, key) => { var groups = {} array.forEach(function(item) { var value = item[key] groups[value] = groups[value] || [] groups[value].push(item) }) return groups } console.log('sorted', sorted(items, 'type'))上述方法只能根据一个属性重新分组,参考网上其他方法:
const sorted = this.groupBy(items, function(item) { return [item.type] //可添加多个属性 }) console.log('sorted', sorted) //method groupBy(array, f) { var groups = {} array.forEach(function(item) { var group = JSON.stringify(f(item)) groups[group] = groups[group] || [] groups[group].push(item) }) return Object.keys(groups).map(function(group) { return groups[group] }) }