Tuesday, July 29, 2014

JavaScript:To get subset of arrays based on the array object property using map and filter

It is easier to do this using LINQ in C#.
However there is no LINQ in Javascript....
To get subset of arrays based on the property

//company_To_Search is an array of object : { name:"xxx", selected: true}
var companySelected = company_To_Search.filter( function( obj ) {
      return obj.selected;
   });
OR

   // To get an array of 'name' property
   var companySelected = company_To_Search.map( function( obj ) {
     if(obj.selected) return obj.name;
   }).filter( function( obj ) {
     return typeof obj !== 'undefined';
   });

 //another example to get a list of Id of the object array
  filters.CompoundFreq = initCriteria.CompoundFreqs.map( function( obj ) {
     return obj.Id;
   }).filter( function( obj ) {
     return typeof obj !== 'undefined';
   });
using underscore reduce:
// To get an array of 'name' property companySelected = _.reduce(company_To_Search, function(memo, company) { if (company.selected) { memo.push(company.name); } return memo; }, []);
using underscore pluck:
// To get an array of 'name' property _.pluck(_.filter(companySelected, function(company) { return company.selected; }), "name");

No comments:

Post a Comment