[英]How to concatenate indefinite number of arrays of Javascript objects
I have an array of Groups st each Group has many Users我有一组组 st 每个组有很多用户
I want to return all (unique) Users for a given array of Groups.我想返回给定组数组的所有(唯一)用户。
So far, I have到目前为止,我有
let actor = await User.query().findById(req.user.id).eager('groups') // find the actor requesting
let actor_groups = actor.groups // find all groups of actor
if (actor_groups.length > 1)
var actor_groups_users = actor_groups[0].user
for (let i = 0; i < actor_groups.length; i++) {
const actor_groups_users = actor_groups_users.concat(actor_groups[i]);
}
console.log('actor groups users is', actor_groups_users);
else
// return users from the first (only) group
which returns the error: actor_groups_users is not defined
返回错误:
actor_groups_users is not defined
Feels like a roundabout way to do this.感觉像是一种迂回的方式来做到这一点。 Is there a way to just combine actor_groups into a single combined group?
有没有办法将 actor_groups 组合成一个组合组?
You can simply do this:你可以简单地这样做:
const allGroupsArrs = actor_groups.map(({ user }) => user);
const actor_groups_users = [].concat(...allGroupArrs);
Or, you could simply use the .flat()
method, which is not yet officially part of the ES standard, but is on its way there and has browser support outside of IE:或者,您可以简单地使用
.flat()
方法,该方法还不是 ES 标准的正式组成部分,但正在开发中,并且具有 IE 之外的浏览器支持:
const allGroupsArrs = actor_groups.map(({ user }) => user);
const actor_groups_users = allGroupArrs.flat();
Also, the above would result in duplicate values in actor_groups_users
if there are people who are in multiple groups.此外,如果有人在多个组中,上述内容将导致
actor_groups_users
出现重复值。 You can remedy this (assuming the array elements are primitive values) using a Set
:您可以使用
Set
解决这个问题(假设数组元素是原始值):
const unique_users = [...new Set(actor_groups_users)];
Here we can cycle through, adding users if not already in the array, using .forEach() and .includes() .在这里,我们可以循环使用.forEach()和.includes()来添加用户(如果不在数组中) 。
This is assuming that group.user
is an Array of users.这是假设
group.user
是一个用户数组。
let users = [];
// check that actor_groups has items in it
if (actor_groups && actor_groups.length > 1) {
// cycle through each actor_group
actor_groups.forEach( group => {
// check if we have a 'user' array with items in it
if (group.user && group.user.length > 1) {
// cycle through each user in the group
group.user.forEach( user => {
// check if we already have this user
// if not, add it to users
if (!users.includes(user)) {
users.push(user);
}
}
}
}
}
The most efficient way I can think of is我能想到的最有效的方法是
const users = [...new Set([...actor_groups].flatMap(el => el.user))]
I used this example:我用了这个例子:
const actor_groups = [{user: ['ok','boom']}, {user: 'er'}]
console.log([...new Set([...actor_groups].flatMap(el => el.user))])
//output: ["ok", "boom", "er"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.