1. 程式人生 > >underscorejs之 _.indexBy(list, iteratee, [context])

underscorejs之 _.indexBy(list, iteratee, [context])

blog element obj userinfo smi pre arguments clone 應該

語法

_.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])