Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At underscore js, Can I get multiple columns with pluck method after input where method as linq select projection

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.

like image 257
ttacompu Avatar asked Oct 13 '13 20:10

ttacompu


People also ask

How do you pluck in JavaScript?

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.

What is underscore js used for?

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.

Can JavaScript function include underscore?

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.

What is _ each in JavaScript?

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.


1 Answers

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)

like image 170
McGarnagle Avatar answered Sep 21 '22 14:09

McGarnagle