underscorejs之 _.indexBy(list, iteratee, [context])
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了underscorejs之 _.indexBy(list, iteratee, [context])相关的知识,希望对你有一定的参考价值。
语法
_.indexBy(list, iteratee, [context])
说明
给定一个list,和 一个用来返回一个在列表中的每个元素键 的iterator 函数(或属性名), 返回一个每一项索引的对象。和groupBy非常像,但是当你知道list的key是唯一的时候可以使用indexBy**。
什么时候用_.indexBy?
api都会给我们返回类似下面这样子的数据,现在我们要写一个方法。传入id,返回相对应的name或是其他。
var data = [{ id: 1, name: ‘Jon Doe‘, birthdate: ‘1/1/1991‘, height: ‘5 11‘ }, { id: 2, name: ‘Jane Smith‘, birthdate: ‘1/1/1981‘, height: ‘5 6‘ }, { id: 3, name: ‘Rockin Joe‘, birthdate: ‘4/4/1994‘, height: ‘6 1‘ }, { id: 4, name: ‘Jane Blane‘, birthdate: ‘1/1/1971‘, height: ‘5 9‘ }]; function getUserInfoById(id){ //写一些代码,可能是这样子的 return _.find(data, function(element, index, list){ return element.id == id; }); } console.log(getUserInfoById(1)); //=> Object {id: 1, name: "Jon Doe", birthdate: "1/1/1991", height: "5 11"} console.log(getUserInfoById(3)); //=>Object {id: 3, name: "Rockin Joe", birthdate: "4/4/1994", height: "6 1"} //但是你很快发现,每次都遍历data里面的数据,如果频繁的取用户信息,应该把data的数据重组一下。 //这时候_.indexBy就华丽的上场了。 var dataClone = _.indexBy(data, ‘id‘); //这样子好多了。 console.log(dataClone[1]); //=> Object {id: 1, name: "Jon Doe", birthdate: "1/1/1991", height: "5 11"} console.log(dataClone[3]); //=>Object {id: 3, name: "Rockin Joe", birthdate: "4/4/1994", height: "6 1"}
代码示例
示例一:list可以是数组、对象、字符串、arguments等
var result1 = _.indexBy(‘1234‘); var result2 = _.indexBy([1, 2, 3, 4]); var result3 = _.indexBy({a:1, b:2, c: 3}); var result4 (function(){ result4 = _.indexBy(arguments); }(1, 2, 3)); console.log(result1); //=> Object {1: "1", 2: "2", 3: "3", 4: "4"} console.log(result2); //=> Object {1: 1, 2: 2, 3: 3, 4: 4} console.log(result3); //=> Object {1: 1, 2: 2, 3: 3} console.log(result4); //=> Object {1: 1, 2: 2, 3: 3}
示例二:iteratee的参数
var result1 = _.indexBy(‘1234‘, function(value, index, list){ console.log(value, index, list); });
示例三:和_.groupBy对比
var stooges = [{name: ‘moe‘, age: 40}, {name: ‘iori‘, age: 40}, {name: ‘larry‘, age: 50}]; var by1 = _.groupBy(stooges, ‘age‘); var by2 = _.indexBy(stooges, ‘age‘); console.log(by1); //=> Object {"40": [{name: ‘moe‘, age: 40}, {name: ‘iori‘, age: 40}], "50": {name: ‘larry‘, age: 50}} console.log(by2); //=> Object {"40": {name: ‘iori‘, age: 40}, "50": {name: ‘larry‘, age: 50}}
示例四:context改成iteratee内的this
var stooges = [{name: ‘moe‘, age: 40}, {name: ‘iori‘, age: 40}, {name: ‘larry‘, age: 50}]; var by1 = _.groupBy(stooges, function(value, index, list){ console.log(this); }, {text : ‘text‘});
以上是关于underscorejs之 _.indexBy(list, iteratee, [context])的主要内容,如果未能解决你的问题,请参考以下文章
underscorejs之_.find(list, predicate, [context])
underscorejs之_.countBy(list, iteratee, [context])
underscorejs之_.map(list, iteratee, [context])
underscorejs之_.contains(list, item, fromIndex, guard)