javascript - 如何在 v-for 循环中匹配两个数组的并集
问题描述
我有两个数组:users
和projects
. 两者中的 ID 都是唯一的数字。一个项目可以有多个所有者,因此在projects
我有一组用户 ID,命名为ownersId
链接到 中id
的用户users
,如下所示:
export const users = [{
id: 1,
givenName: 'Alexander',
surname: 'Kelly',
initials: 'AK'
}, {
id: 2,
givenName: 'Karen',
surname: 'Jones',
initials: 'KJ'
}, {
id: 3,
givenName: 'Casey',
surname: 'Fields',
initials: 'CF'
}, {
id: 4,
givenName: 'Sam',
surname: 'Johns',
initials: 'SJ'
}, {
id: 5,
givenName: 'Thomas',
surname: 'Smith',
initials: 'TS'
}, {
id: 6,
givenName: 'Jack',
surname: 'Jenson',
initials: 'JJ'
}];
export const projects = [{
id: 1,
name: 'Project 1',
ownersId: [
1,
2,
5,
6,
]}, {
id: 2,
name: 'Project 2',
ownersId: [
1,
3,
]}, {
id: 3,
name: 'Project 3',
ownersId: [
1,
2,
4,
3,
]}, {
id: 4,
name: 'Project 4',
ownersId: [
1,
]}, {
}]
我正在尝试做的是循环project
使用我已成功完成的详细信息v-for
。我坚持的是在循环中显示一个循环,该循环使用字段users
中的 ID 显示所有名称。ownersId
<template>
<div class="demo">
<div
v-for="project in projects"
v-bind:key="project.id"
>
<h4><strong>{{ project.name }}</strong></h4>
<div v-if="project.ownersId" >
Shared with {{ project.ownersId.length }} others
</div>
<div>
<!-- Loop of the list of names from IDs goes here -->
</div>
</div>
</div>
</template>
<script>
import { projects } from '../data/example';
import { users } from '../data/example';
export default {
name: "Demo",
data() {
return {
projects,
users,
}
}
}
</script>
解决方案
将您的用户数据数组转换为计算对象以便快速查找。然后将只有 1 次数据迭代,以创建对象。该对象也将被缓存,因为它是计算的,因此重新渲染不会再次触发迭代。
这可以防止大量多余的数组循环和查找,这对于较大数据集的性能可能很重要,尤其是在模板因任何原因重新渲染时。
computed: {
userData() {
const userData = {};
this.users.forEach(user => {
userData[user.id] = user;
});
return userData;
}
}
模板
<div
v-for="project in projects"
v-bind:key="project.id"
>
<h4><strong>{{ project.name }}</strong></h4>
<div v-if="project.ownersId" >
Shared with {{ project.ownersId.length }} others
</div>
<div>
<div v-for="userId in project.ownersId" :key="userId">
{{ userData[userId] }}
</div>
</div>
</div>
这是一个演示
推荐阅读
- arrays - 修改循环内列表的不同索引
- java - 回收器适配器中菜单的 setOnMenuItemClickListener
- c# - 通过字符串操作从json字符串中读取值
- windows - 在 WSL(Linux 的 Windows 子系统)上挂载磁盘映像?
- html - 谷歌验证码上的自定义光标
- bpf - eBPF 程序将 HTTP 请求转发到不同的端口
- javascript - 如何使用 React 中的 fetch api 访问从前端服务器返回的响应消息?
- php - 通过更新多行删除不需要的内容
- twitter-bootstrap - 引导轮播不适用于烧瓶路由
- bigbluebutton - BigBlueButton 错误 - 设置 TURN 服务器后出现错误 500