Underscore.JS - indexBy 方法
语法
_.indexBy(list, iteratee, [context])
indexBy 方法获取按提供的 iteratee 方法返回的索引分组的拆分列表。
示例
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} ] //示例 1. 调用 indexBy 方法获取按成本索引的对象 var result = _.indexBy(list, 'Cost'); console.log(result); //示例 2. 调用 indexBy 方法获取按作者索引的对象 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 } }
underscorejs_processing_collection.html