Sintaxe
_.indexBy(list, iteratee, [context])
O método indexBy obtém as listas distribuídas agrupadas por índice retornado pelo método iteratee fornecido.
Exemplo
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)
Salve o programa acima em tester.js. Execute o seguinte comando para executar este programa.
Comando
\>node tester.js
Resultado
{
'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 }
}