javascript 按对象键过滤对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15274632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter array of objects by object key
提问by rpabon
I have an array of objects in Javascript:
我在 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.
我想获得两个新的对象数组;一个给关键员工“Joe”,另一个给关键员工“Jerry”。对象应该保持相同的键/值对。
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?
我一直在尝试使用 underscore.js 获得解决方案,但它变得太复杂了。关于如何实现这一目标的任何想法?
Thanks in advance
提前致谢
回答by Ben McCormick
var joe = List.filter(function(el){
return el.employee === "Joe"
});
var jerry = List.filter(function(el){
return el.employee === "Jerry"
});
This uses Array.prototype.filterand will work in IE9 and up + all recent Chrome/Firefox/Safari/Opera releases.
这使用Array.prototype.filter并将在 IE9 及更高版本 + 所有最近的 Chrome/Firefox/Safari/Opera 版本中工作。
If you don't know the names in advance then you can create a map var names = {};
如果您事先不知道名称,那么您可以创建一个地图 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.
作为旁注,Javascript 约定是仅将构造函数的变量的第一个字母大写。所以列表应该是列表。
回答by Diode
var emps = {};
_.each(List, function(item){
emps[item.employee] = emps[item.employee] || [];
emps[item.employee].push(item);
});
or using groupBy
或使用 groupBy
var emps = _.groupBy(List, function(item){
return item.employee;
});
console.log(emps);
gives
console.log(emps);
给
{
"Jerry": [
{
"employee": "Jerry",
"type": "seminar"
}
],
"Joe": [
{
"employee": "Joe",
"type": "holiday"
},
{
"employee": "Joe",
"type": "shore leave"
}
]
}
回答by GenKali
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.
否则@Ben 给出的答案是完美的 - 如果在项目中使用下划线是不可能的,它可以扩展为“groupby”函数。