Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects by object key

I have an array of objects in Javascript:

var List = [
            {
                employee:'Joe',
                type:'holiday',
            },
            {
                employee:'Jerry',
                type:'seminar',

            },
            {
                employee:'Joe',
                type:'shore leave',
            }
           ];

I would like to obtain two new arrays of objects; one for the key employee "Joe" and the other for the key employee "Jerry". The objects should keep the same pairs of key/values.

I have been trying to get a solution using underscore.js, but it is getting too complicated. Any ideas on how this can be achieved?

like image 331
rpabon Avatar asked Oct 30 '25 20:10

rpabon


1 Answers

var joe = List.filter(function(el){
 return el.employee === "Joe"
});

var jerry = List.filter(function(el){
 return el.employee === "Jerry"
});

This uses Array.prototype.filter and will work in IE9 and up + all recent Chrome/Firefox/Safari/Opera releases.

If you don't know the names in advance then you can create a map var names = {};

for(var i =0; i<List.length; i++){
  var ename = List[i].employee;
  if(typeof names[ename] === "undefined"){
     names[ename] = List.filter(function(el){
     return el.employee === "ename"
    });
   }

}

As a side note, Javascript convention is to only capitalize the first letter of a variable for constructors. So List should probably be list.

like image 164
Ben McCormick Avatar answered Nov 01 '25 09:11

Ben McCormick