_.indexBy(list, iteratee, [context])
给定一个list,和 一个用来返回一个在列表中的每个元素键 的iterator 函数(或属性名), 返回一个每一项索引的对象。和groupBy非常像,但是当你知道list的key是唯一的时候可以使用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"}
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}
var result1 = _.indexBy('1234', function(value, index, list){
console.log(value, index, list);
});
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}}
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'});