首页 > 解决方案 > 如何在 v-for 循环中匹配两个数组的并集

问题描述

我有两个数组:usersprojects. 两者中的 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>

标签: javascriptarraysvue.jsvuejs2vue-component

解决方案


将您的用户数据数组转换为计算对象以便快速查找。然后将只有 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>

这是一个演示


推荐阅读