Underscore.JS indexBy 方法
语法
_.indexBy(list, iteratee, [context])
indexBy方法通过提供的迭代器方法返回的索引对拆分的列表进行分组。
示例
var _ = require('underscore');
var list = [{"title": "Learn Java", "Author": "Sam", "Cost": 100},
{"title": "Learn Scala", "Author": "Joe", "Cost": 200},
{"title": "Learn C", "Author": "Julie", "Cost": 300} ]
//Example 1. invoke indexBy method to get objects indexed by their cost
var result = _.indexBy(list, 'Cost');
console.log(result);
//Example 2. invoke indexBy method to get objects indexed by their author
result = _.indexBy(list, 'Author')
console.log(result)
将上面的程序保存在 tester.js 中。运行以下命令执行该程序。
命令
>node tester.js
输出
{
'100': { title: 'Learn Java', Author: 'Sam', Cost: 100 },
'200': { title: 'Learn Scala', Author: 'Joe', Cost: 200 },
'300': { title: 'Learn C', Author: 'Julie', Cost: 300 }
}
{
Sam: { title: 'Learn Java', Author: 'Sam', Cost: 100 },
Joe: { title: 'Learn Scala', Author: 'Joe', Cost: 200 },
Julie: { title: 'Learn C', Author: 'Julie', Cost: 300 }
}