最近项目中后台给返回的数据很复杂,须要各类遍历,组合,其中Object.keys(obj)和经过封装的groupBy这两个方法带给了我极大的便利数组
/* Array 对象 */ let arr = ["a", "b", "c"]; console.log(Object.keys(arr)); // ['0', '1', '2'] /* Object 对象 */ let obj = { foo: "bar", baz: 42 }, console.log(Object.keys(obj)); // ["foo","baz"] /* 类数组 对象 */ let obj = { 0 : "a", 1 : "b", 2 : "c"}; console.log(Object.keys(obj)); // ['0', '1', '2']
Array.prototype.groupBy = function(prop) { return this.reduce(function(groups, item) { var val = item[prop]; groups[val] = groups[val] || []; groups[val].push(item); return groups; }, {}); } var myList = [ {time: '12:00', location: 'mall' }, {time: '9:00', location: 'store' }, {time: '9:00', location: 'mall' }, {time: '12:00', location: 'store' }, {time: '12:00', location: 'market' }, ]; var byTime = myList.groupBy('time'); byTime = { '9:00': [ {time: '9:00', location: 'store' }, {time: '9:00', location: 'mall' }, ], '12:00': [ {time: '12:00', location: 'mall' }, {time: '12:00', location: 'store' }, {time: '12:00', location: 'market'} ] }
var total = [0, 1, 2, 3].reduce(function(sum, value) { return sum + value; }, 0); // total is 6 var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) { return a.concat(b); }, []); // flattened is [0, 1, 2, 3, 4, 5]
callback
执行数组中每一个值的函数,包含四个参数:函数
accumulator 累加器累加回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(以下所示)。 currentValue 数组中正在处理的元素。 currentIndex 数组中正在处理的当前元素的索引。若是提供了initialValue,则索引号为0,不然为索引为1。 array 调用reduce的数组
initialValue
[可选] 用做第一个调用 callback的第一个参数的值。若是没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。this
Array.prototype.groupBy = function(prop) { return this.reduce(function(groups, item) { var val = item[prop]; // 取出time 例如 9:00 groups[val] = groups[val] || []; // 每一次取出groups中的9:00对象,若是存在(覆盖一次),若是是12:00对象则赋值新数组 groups[val].push(item); return groups; }, {}); }