var people = [ {firstName : "Thein", city : "ny", qty : 5}, {firstName : "Michael", city : "ny", qty : 3}, {firstName : "Bloom", city : "nj", qty : 10} ]; var results=_.pluck(_.where(people, {city : "ny"}), 'firstName');
For example : I need firstName
and qty
.
pluck() function is used when we need to extract a list of a given property. Like we have to find out the name of all the students, then we can simply apply the _. pluck() function on the details of all the students. It will only extract the name from the details of all the stuf=dents and display it.
Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.
Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private.
Collection Functions (Arrays or Objects) each _.each(list, iteratee, [context]) Alias: forEach. Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed.
To project to multiple properties, you need map
, not pluck:
var results = _.map( _.where(people, {city : "ny"}), function(person) { return { firstName: person.firstName, qty: person.qty }; } );
[{"firstName":"Thein","qty":5},{"firstName":"Michael","qty":3}]
(Fiddle)
Note that, if you wanted to, you could create a helper method "pluckMany" that does the same thing as pluck with variable arguments:
// first argument is the source array, followed by one or more property names var pluckMany = function() { // get the property names to pluck var source = arguments[0]; var propertiesToPluck = _.rest(arguments, 1); return _.map(source, function(item) { var obj = {}; _.each(propertiesToPluck, function(property) { obj[property] = item[property]; }); return obj; }); };
You can use the _.mixin
function to add a "pluckMany" function to the _
namespace. Using this you can write simply:
var results = _.chain(people).where({city : "ny"}).pluckMany( "firstName", "qty").value();
(Fiddle)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With