What is the best way to combine the elements of two arrays within a v-for loop?

Within my code, I have defined two arrays: users and projects. Each array contains unique numbers as IDs. A project can be owned by multiple users, so in the projects array, there is an array of user IDs named ownersId that corresponds to the id of users in the users array. Here’s a snippet of how it looks:

export const users = [{
    id: 1,
    givenName: 'Alexander',
    surname: 'Kelly',
    initials: 'AK'
}, {
    id: 2,
    givenName: 'Karen',
    surname: 'Jones',
    initials: 'KJ'
}, {
    // more user details...
}];
export const projects = [{
    id: 1,
    name: 'Project 1',
    ownersId: [
        1,
        2,
        // more owner IDs...
    ]}, {
    // more project details...
}]

My objective is to iterate over the project details successfully achieved using v-for. However, I am facing a challenge when attempting to display user names associated with the IDs listed in the ownersId field whilst looping through each project.

<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>
                <!-- Nested loop to display user names based on ID -->
            </div>
        </div>
    </div>
</template>

<script>
import { projects } from '../data/example';
import { users }  from '../data/example';

export default {
    name: "Demo",
    data() {
        return {
            projects,
            users,
        }
    }
}
</script>

Answer №1

Transforming your user data array into a computed object can greatly enhance lookup speed. By doing this, you only need to iterate through the data once to create the object. Additionally, since it's a computed object, it will be cached and won't need to be iterated through again during re-renders.

This optimization can help reduce unnecessary array looping and searching, which is crucial for performance when dealing with large datasets, especially if the template needs to be re-rendered frequently.

computed: {
  userData() {
    const userData = {};
    this.users.forEach(user => {
      userData[user.id] = user;
	});
	return userData;
  }
}

Template

<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>

Check out the demo.

Answer №2

Welcome to the world of software development.

When dealing with two arrays, it's efficient to create a method that retrieves user data based on the project and then iterate through that data.

methods:{
 getUserList(project){
  return project.ownersId.map(id=>
    users.find(user=>user.id===id)
   )
 }
}

You can utilize this method in the following manner:

<div v-for="project in projects" :key="project.id">
...
  <!-- Display list of names from IDs here -->
  <template v-for="user in getUserList(project)" :key="user.id"> 
    {{ user }}
  </template>
...
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of this hint regarding the Vue devtools version?

While checking my Vue devtools, I noticed a version hint displayed: I am confused about the origin of the version number 3.2.28 mentioned in the hint. My current Vue version is actually 3.2.25. ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...

Sending a form cancellation submission within a nested function call

I need help preventing my form from submitting in case the confirmation message is cancelled. How can I achieve this within the each() loop? $('#myForm').submit(function() { var inputs = $(this).find('input:checked'); inputs.ea ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...

Sort data by various categories using Vue.js

I need help filtering my JSON data based on multiple categories using Vuejs, specifically with Vue 3 and collect.js. Here's the template I'm working with: <select v-model="selectedCategory" multiple> <option :value="n ...

React: maintaining referential equality across renders by creating closures with useCallback

I want to make sure the event handling function I create in a custom hook in React remains referentially equal across renders. Is it possible to achieve this using useCallback without specifying any variables it closes over in the dependencies list? Will o ...

How can Vue JS 3 components exchange data between each other?

I am attempting to share data from a variable favorite_count in the Favorites component located in the file Favorites.vue. My goal is to pass this data to the App Component in the App.vue file but I have been unsuccessful so far. I want any changes made to ...

Jquery feature to automatically hide the submit button

Is there a way to automatically hide the submit button and display a message without requiring a mouse click? If the main balance is less than the inputted withdrawal amount, I want the submit button to be hidden automatically and a message stating insuff ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

Guide to adding personalized SVG symbols to Vuetify 3

Looking to import custom SVG icons in Vuetify 3 and Nuxt 3? In Vuetify 2, we could import SVG icons directly like this import customIcon from './myIcon.vue' Vue.use(Vuetify) export default new Vuetify({ icons: { iconfont: 'mdi', ...

Import JSON Data into Angular-nvD3 Chart (AngularJS)

I am seeking help to load encoded JSON Data retrieved from a database via queries into an Angular-nvD3 graph. I am unsure about the best approach to achieve this task. The encoded JSON data is fetched using API queries from a database table called PRODUCT ...

"Access denied" error when using Internet Explorer and jQuery

Attempting to make an AJAX call using jQuery's $.post in Internet Explorer is resulting in an error message stating "Permission denied." This peculiar issue only seems to occur when accessing a page after having visited another page. For example, if ...

Authenticate users using Laravel's default authentication system, then serve the Vuejs single page application only to logged

Currently working on a Single Page Application using the default Laravel scaffolding: // Setting up basic scaffolding... php artisan ui vue // Implementing login / registration features... php artisan ui vue --auth These commands provide a solid foundati ...

How come I am receiving {"readyState":1} in the DOM instead of JSON data in AngularJS?

Currently, I am facing an issue where instead of the JSON data (which consists of only 49 items) showing up on the DOM, I am getting {"readyState":1}. I believe this is just a test to ensure that my code is functioning correctly. Although I have identifie ...

Troubleshooting Vue.js rendering problems on Safari_BROWSER

I'm encountering a strange issue with my portfolio website, which is built using Vue and Laravel. The problem arises specifically in Safari - the project thumbnails don't display until the browser window is resized. Here's the relevant code ...

How can we display the data returned by a successful AJAX request

Having an issue with displaying Ajax success data. success: function(data){ alert(need to print it here); } When I try to access the data using: console.log(data.responseText); {"success":false,"errors":{"text":["Some text.","some more text"]}} Any ...

Developing a website using custom modules in Node.js and Express framework

I am currently encountering an issue when using a custom module within one of my route functions in Express with node. Below is my current setup: In the app.js file, I require the module as follows: c_controller = require( './core/c_controller' ...

Enhancing user interfaces with jQuery by updating DOM elements

Can anyone help me figure out how to update a webpage so it functions as a report that multiple people can contribute to? I'm using forms to collect data and want it to instantly display under the correct category headings. Currently, I'm using j ...

What is the method for determining the mean value of items in a three-dimensional array?

I am attempting to calculate the average value for certain parameters and then create a plot using a predefined function. My plan is to populate a 3-column array with values, take the average of those values, and then plot them after creating 1000 values f ...