对象的滤镜阵列由对象键 [英] Filter array of objects by object key
本文介绍了对象的滤镜阵列由对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对象在Javascript数组:
VAR列表= [
{
员工:'乔',
类型:'假期',
},
{
员工:杰里,
类型:'研讨会', },
{
员工:'乔',
输入:'上岸',
}
];
我想获得对象的两个新的阵列;一个关键员工乔,另一个关键员工杰里。该对象应该保持相同的对键/值。
我一直在试图让使用underscore.js一个解决方案,但它越来越太复杂了。如何可以做到这一点任何想法?
在此先感谢
解决方案
VAR的emps = {};
_.each(列表,功能(项目){
EMPS [item.employee] = EMPS [item.employee] || [];
EMPS [item.employee] .push(项目);
});
或使用 GROUPBY
VAR的emps = _.groupBy(表,函数(项目){
返回item.employee;
});
的console.log(EMPS);
给
{
杰里:[
{
员工:杰里
类型:研讨会
}
]
乔:[
{
员工:乔,
类型:假日
},
{
员工:乔,
类型:上岸
}
]
}
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
解决方案
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"
}
]
}
这篇关于对象的滤镜阵列由对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文