Filter array of objects by object key

南楼画角 提交于 2019-12-09 01:07:09

问题


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?

Thanks in advance


回答1:


var emps = {};  
_.each(List, function(item){
   emps[item.employee] = emps[item.employee] || [];
   emps[item.employee].push(item);
});

or using groupBy

var emps = _.groupBy(List, function(item){
   return item.employee;
});

console.log(emps); gives

{
    "Jerry": [
        {
            "employee": "Jerry",
            "type": "seminar"
        }
    ],
    "Joe": [
        {
            "employee": "Joe",
            "type": "holiday"
        },
        {
            "employee": "Joe",
            "type": "shore leave"
        }
    ]
}



回答2:


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.




回答3:


Sorry - I don't have the rep. to comment yet but I believe it should be

return el.employee === ename;  // No quotes around ename

Otherwise the answer @Ben gives is perfect - it can be extended into a 'groupby' function if using underscore is out of the question a the project.



来源:https://stackoverflow.com/questions/15274632/filter-array-of-objects-by-object-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!