Underscore.JS - Méthode indexBy

Syntaxe

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

La méthode indexBy récupère les listes spiltées regroupées par index retourné par la méthode iteratee fournie.

Exemple

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)

Enregistrez le programme ci-dessus dans tester.js. Exécutez la commande suivante pour exécuter ce programme.

Commander

\>node tester.js

Production

{
  '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 }
}