Looping precisely five times in Vue3JS over an array and conditionally verifying each element within

After spending the past 2 hours searching through similar subjects on SO without success, I am turning to you for help.

My goal is to create a scoreboard displaying results in the following format:

  • John Doe 100 pts
  • John Smith 50 pts
  • No Name
  • No Name
  • No Name

I have an array named scoreBoardArray containing the necessary data.

data() {
  return {
     scoreBoardArray: [
        { id: '1', name: 'John Doe', pts: 100 },
        { id: '2', name: 'John Smith', pts: 50 },
     ],
   }
},

I have attempted to loop through this array and display the names and points exactly 5 times, filling in with "No Name" when no record is found.

This is my code (and attempts to solve the issue):

<ul>
   <li v-for="item in scoreBoardArray" :key="item.id">
      <span v-if="item.id">{{ item.name }} {{ item.pts }}</span>. 
      <span v-else>No Name</span>
   </li>
</ul>

Despite trying to use a computed property and a basic loop like for(let i=0; i<6; i++) {...}, I haven't been successful in solving the issue.

Answer №1

To extract the first 5 elements in the scoreBoardArray[] and determine how many "No Name" dummy items are required, you can utilize a computed property named topScores for the top scores and dummyLength to calculate the number of dummy items needed:

export default {
  computed: {
    topScores() {
      return this.scoreBoardArray
        .slice()                      // create a copy
        .sort((a,b) => b.pts - a.pts) // sort by points
        .slice(0, 5)                  // get first 5 elements
    },
    dummyLength() {
      return Math.max(0, 5 - this.topScores.length)
    }
  }
}

Update the template to display the computed properties using a v-for, showing the topScores followed by dummyLength for the dummy items:

<ul>
  <li v-for="item in topScores" :key="item.id">
    <span>{{ item.name }} ({{ item.pts }})</span>
  </li>
  <li v-for="n in dummyLength">No Name</li>
</ul>

Check out the demo.

Answer №2

If you need to expand your array to a specific length, consider using a computed property.

One approach is to add empty objects to the end of your array until it reaches 5 values.

computed: {
  expandedArray() {
    let padding = []
    const paddingCount = 5 - this.originalArray.length
    for (let i = 0; i < paddingCount; i++) {
      padding[i] = {}
    }
    return [...this.originalArray, ...padding]
  }
}

Keep in mind that when adding empty objects, you may face issues with v-for loop keys. To address this, consider using indices as keys:

<li v-for="(item, index) in expandedArray" :key="index">

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

Tips for asynchronously adding data (requires two iterations) to an API service in Angular

I have a json file structured as follows: { "users": [ { "id": "person1", "information": [ { "first_name": "Mike", "last_name": "Patty" ...

Creating a flexible grid layout that adjusts to show either one or two columns on smaller mobile screens

NOTE: This is not a duplicate as the layout order for columns and rows is specifically tailored for mobile devices. I am attempting to showcase this grid design on mobile devices with the following sequence: First row: header (1 column, full width) Secon ...

Could not complete operation: EPERM error indicating permission denied for 'stat' operation

Recently delving into Firebase Functions for my Flutter project has been a game-changer. Discovering the code generator, firebase_functions_interop, that seamlessly transforms Dart code into Javascript has made developing cloud functions in Dart a breeze. ...

Steps for updating the homepage to display a personalized welcome message to the user after logging in and redirecting using node.js and

Upon arriving at the homepage, simply click on the sign-in button. Once redirected back to the home page, you will notice a personalized greeting saying 'Welcome [user]'. Wondering how to achieve this? It's as simple as changing the text fro ...

Ways to conceal a React component when route transitions occur

I am currently utilizing the location prop from react router dom to set my state to false and only render a component if it's true. Below is an example of how I achieve this in React: const [ showFilter, setShowFilter ] = useState(false); const locati ...

What could be causing the Monster model to not appear when using the glTFLoader in three.js on iOS?

-Details- three.js version : r84 (current version) Device : iPad Air2 iOS version : 10.0.2 Browser : Chrome, Safari -glTFLoader- URL : Monster -> NOT visible The rest -> visible Why am I asking this question? I have encountered a similar is ...

Using React Native to iterate over a multidimensional array with the array map function

I want to iterate through a two-dimensional array like the one below: var array=[["1"],["3","8"],["4","8","3"],["4","8","3","9"],["1","8","3","9","2"],["6","8","3","9","2","1"],["4","8","3","9","2","11","2"]] Currently, this code only loops through the & ...

Access to the Heroku app is restricted to the specific device that I have designated for its

I am having some issues with deploying my app and need some help. Here are the details: Using the free plan on Heroku On other devices, only the background image/color/pattern is visible Errors on other devices (mainly related to Redux): On Firefox ...

Transferring HTML elements between pages

I'm currently working on a project with 4 tabbed views, each housed in separate HTML pages. Each view contains several SVG charts created using d3.js. Now, the client wants to be able to easily cut, paste, or move charts from one tabbed view to anothe ...

Struggling to retrieve a class within an <a> element in jsTree when hovering?

I'm currently utilizing jsTree and below is how I'm initializing it... function setupJSTree(data){ $("#treeSelector").jstree({ "plugins" : ["themes","json_data","UI","types"], "themes" : { "theme":"def ...

Can the name of the Grunt task target be utilized within attributes?

I have implemented the grunt-replace task to make some content changes in the index.html file. However, I am looking for a way to avoid repeating code unnecessarily. The code snippet below is just an example of what I am trying to accomplish: replace: { ...

The output of server.address() method in Node.js is ::

My memory serves me right, a few days back it was showing "localhost". I'm puzzled as to what altered server.address().address to now return double colons (::). According to my research, it seems to be returning an IPv6 address (::) because it's ...

Is there a way for me to identify the value within useCallback without any intermediaries?

How can I ensure that console.log('success') is triggered when the ids of myFood[myFood.length - 1]?.id and viewableItems[viewableItems.length - 1]?.item?.id match? Despite both values being equal, there seems to be an issue preventing console.l ...

Issue with Three.js: real-time color updating for mesh not functioning

Attempting to create a simple program with an animation that switches the color of a traffic light from green to red and back every 2 seconds, but the color change is not working as expected. I have tried debugging the code by printing the booleans that s ...

creating a checkerboard using an array of JPanels

I am currently working on creating a chessboard by using an array of JPanels, where each box represents a JPanel with a specific color. However, I am encountering an issue when I try to make the assignment "chessboard[rows][columns] = b" as it results in a ...

Here is a step-by-step guide on how to use JavaScript to eliminate the page title, URL, date and

When printing a page using window.print, is there a way to exclude the page title, URL, page number, and date/time from appearing? ...

What is the best way to insert a "Read More" link following a short snippet of text

I am looking to implement multiple "read more" links to enable users to continue reading after a specified amount of text, such as 1000 words or 2 paragraphs. <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script&g ...

Attempting to categorize JSON object elements into separate arrays dynamically depending on their values

Here's the JSON data I'm currently working with: ?$where=camis%20=%2230112340%22 I plan to dynamically generate queries using different datasets, so the information will vary. My main objective is to categorize elements within this array into ...

Authenticating Vue.js / Axios requests to an API route in Laravel: A step-by-step guide

I've been working with Laravel 5.6 and have successfully set up all my API routes, which are responding to requests from my REST client (Paw). Now, I want to create a basic front end to interact with these routes. In an effort to utilize Laravel&apos ...

Ways to display additional information in typeahead using Angular JS

Currently, I am using the Bootstrap directory typeahead in Angular. I am looking to display more results in my HTML template instead of just the name: typeahead="job as job.name for job in getJobPlace($viewValue) | filter:{name:$viewValue}" I would like ...