1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| var arr = [ {tag: 'a', name: 1, age: 2}, {tag: 'b', name: 3, age: 4}, {tag: 'a', name: 5, age: 6}, {tag: 'b', name: 7, age: 8}, {tag: 'c', name: 7, age: 8}, {tag: 'b', name: 1, age: 2}, {tag: 'b', name: 3, age: 4}, {tag: 'd', name: 5, age: 6}, {tag: 'b', name: 7, age: 8}, {tag: 'd', name: 7, age: 8}, ]
const groupBy = (arr, key, child) => arr.reduce((t, v, i) => { let findIndex = [].concat(t).findIndex(e => e[key] === v.tag) if ( findIndex > -1) { t[findIndex][child] = t[findIndex][child].concat([{name: v.name, age: v.age}]) } else { t.length += 1 t[t.length - 1] = {} t[t.length - 1][key] = v[key] t[t.length - 1][child] = [].concat([{name: v.name, age: v.age}]) } return t }, [])
console.log(groupBy(arr, 'tag', 'arr'))
|