我有一个群体对象:
{groupid1: "metadata",
groupid2: "metadata"}
以及一系列用户:
[
{
name: "something",
groups: ["groupid1", "groupid2"]
...},
{
name: "something else ",
groups: ["groupid1"]
...},
{
name: "something else again",
groups: ["groupid2"]
...},
]
我想迭代组ID并提取与该组ID匹配的用户列表,因此我最终记录了两个用户列表,每组一个:
for (group in groups) {
var userArray = _.pluck(users, function(user) {
return user.groups.indexOf(group) > -1;
})
console.log(userArray);
}
问题是这会返回一个未定义的数组,而不是一组用户对象。即使只是返回用户的名字也不错。
感谢您提供任何帮助! 对于可伸缩性,下划线是解决此问题的首选方法。
答案 0 :(得分:1)
正如docs _.pluck()
中所述,有两个参数:列表和属性名称 - 您不提供属性名称而是提供函数。更重要的是,这不是您使用_.pluck()
函数的原因(再次查看文档)。
在您的情况下,您根本不需要使用UnderscoreJS:
// Your groups
const groups = {
groupid1: "metadata",
groupid2: "metadata"
};
// Your users
const users = [
{
name: "something",
groups: ["groupid1", "groupid2"],
},
{
name: "something else ",
groups: ["groupid1"]
},
{
name: "something else again",
groups: ["groupid2"]
}
];
// Get ids of the groups and loop through them
const result = Object.keys(groups).forEach(groupId => {
// Return only users whose groups array contains the groupId
const usersFound = users.filter(user => user.groups.indexOf(groupId) > -1);
// Log the users found
console.log(usersFound);
});

答案 1 :(得分:1)
您的代码段问题在于您使用的是_.pluck
而不是_.select
。
这是underscore.js解决方案:
const groups = {
groupid1: "metadata",
groupid2: "metadata"
};
const users = [{
name: "something",
groups: ["groupid1", "groupid2"]
},
{
name: "something else ",
groups: ["groupid1"]
},
{
name: "something else again",
groups: ["groupid2"]
},
];
_.each(_.keys(groups), group => {
const usersArray = _.select(users, user => {
return user.groups.indexOf(group) > -1;
});
console.log(usersArray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
从这个答案的评论中回答作者的另一个问题:
我想扩展问题,将两者的结果推送到一个数组中,而不是包含重复数据
const groups = {
groupid1: "metadata",
groupid2: "metadata"
};
const users = [{
name: "something",
groups: ["groupid1", "groupid2"]
},
{
name: "something else ",
groups: ["groupid1"]
},
{
name: "something else again",
groups: ["groupid2"]
},
];
let usersArray = [];
_.each(_.keys(groups), group => {
usersArray = _.union(usersArray, _.select(users, user => {
return user.groups.indexOf(group) > -1;
}));
});
console.log(usersArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>