How can Vue JS be used to assign numbers to specific elements in an array that meet certain conditions?

Imagine having an array of objects within your Vue state like the following:

[
 {name: "Daniel", default: false},
 {name: "Ross", default: true},
 {name: "Rachel", default: false},
 {name: "Joey", default: false}
 {name: "Monica", default: true}
 {name: "Gunther", default: true}
]

All these names are already displayed in a list on your webpage. Now, what you want to achieve is as follows:

  • Daniel
  • Ross - Default 1
  • Rachel
  • Joey
  • Monica - Default 2
  • Gunther - Default 3

It's clear from the example above that this is the desired outcome. What is the most straightforward way to accomplish this in Vue?

Answer №1

Consider utilizing the computed property in your code. Review the snippet below for implementation:

const app = new Vue({
  el: '#app',
  data() {
    return {
      list: [
       {name: "Sarah", default: false},
       {name: "Tom", default: true},
       {name: "Alice", default: false},
       {name: "Bob", default: false},
       {name: "Emily", default: true},
       {name: "Charlie", default: true},
      ]
    };
  },
  computed: {
    getList() {
      let index = 1;
      return this.list.map(item => {
        return item.default ? `${item.name} - Default ${index++}` : `${item.name}`;
      });
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template>
 <ul>
  <li v-for="(item, index) in getList" :key="index">
  {{item}}
  </li>
 </ul>
</template>
</div>

Answer №2

To achieve your desired output, Array.map can be utilized to iterate through all elements of an array

const items = [
  { label: "Apple", inStock: true },
  { label: "Banana", inStock: false },
  { label: "Orange", inStock: true },
  { label: "Pear", inStock: false }
];

let stockCount = 0;
const result = items.map(fruit => `${fruit.label}${fruit.inStock ? ` available ${++stockCount}` : ' out of stock'}`)

console.log(result)

Answer №3

Give this a shot:

let defaultCounter = 0;
const info = [
  { name: "Daniel", defaultValue: false },
  { name: "Ross", defaultValue: true },
  { name: "Rachel", defaultValue: false },
  { name: "Joey", defaultValue: false },
  { name: "Monica", defaultValue: true },
  { name: "Gunther", defaultValue: true },
].map((element) => {
  if (element.defaultValue) {
    defaultCounter++;
    return {
      ...element,
      defCount: defaultCounter,
    };
  } else {
    return {
      ...element,
      defCount: null,
    };
  }
});

console.log(info);
<li v-for="(item) in array" :key="item.name">
{{`${item.name}${item.defCount? ` - Default ${item.defCount}`:''}`}}
</li>

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

Exploring Vue.js nested slots: a guide on transferring slots to grandchildren

I have been utilizing various Vuetify components, such as the v-menu. The template structure for this component looks like this: <v-menu> <a slot="activator">menu</a> <v-list> <v-list-tile>Menu Entry 1</v-list-tile ...

The button will continue to be enabled even if the textfield is empty

I have a task to implement a feature on a webpage where the submit button should remain disabled until all values are entered in the textbox. However, I am facing an issue where the submit button is already active when the page loads. .directive('pas ...

Using Vuetify with FontAwesome SVG icons: implementing v-icon/prepend-icon

I'm new to Vue and I'm struggling to figure out how to use FA SVG icons in v-icon and prepend-icon. When I try to use the code below: <font-awesome-icon :icon="dekstop" color="gray"></font-awesome-icon> The icons display correctly. ...

Is it possible to update parent data using a child component?

What is the correct way to update parent data using a child component? In the child component, I am directly modifying parent data through props. I'm unsure if this is the right approach. According to the Vue documentation: When the parent proper ...

What is the best way to swap out an HTML file with another without altering the link?

I'm working on an HTML file, which is basically a webpage. My goal is to create a functionality where clicking a button will dynamically replace the content of the page with another HTML file, complete with its own CSS, JavaScript functions, and other ...

The Bootstrap image slider is limited to showing a single item at a time

I've been attempting to implement a carousel in Bootstrap 4 that displays multiple items at once and allows scrolling one item at a time, but I can't seem to get it right. Despite going through various tutorials and forum posts, the carousel alwa ...

What could be the reason for my React Component not properly associating with the image?

The title appears to be correctly displayed, but there seems to be an issue with the images. I've thoroughly reviewed the code multiple times, but unfortunately, I'm unable to identify the problem. Please provide guidance on what changes need to ...

Program that extracts information from interactive controls

One of my challenges involves working with pages that have dynamic controls, where I never know the types or quantities of controls present. My goal is to create a script that can extract text from a text area when it's clicked. Although I initially b ...

Next.js does not support Video.js functionality when using server side rendering

I'm struggling to set up video.js in my next.js project and encountering issues. When the player is loading, it initially appears black and then disappears abruptly. A warning message in the console reads: "video.es.js?31bb:228 VIDEOJS: WARN: T ...

"Utilizing Rails 3 to initiate an AJAX submit when radio buttons are changed leads to the generation of

Need help with Rails 3 form partial <%= form_for(answer, :remote => true) do |f| %> <% if answer.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(answer.errors.count, "error") %> prevented this ans ...

Tips for placing <div .right> above <div .left> when the window is small, given that <div .right> is positioned to the right of <div .left> when the window is large

I've come across a similar layout before, but I'm struggling to replicate it myself. The idea is to have text aligned on the left side with an image floated to the right. Instead of the image appearing below the text when the window size is red ...

The navigation underline stays in place even after being clicked, and also appears below

Take a look at this js fiddle I've managed to create the underline effect on the navigation links when the user hovers over them. However, the underline only stays visible until the user clicks elsewhere on the screen. How can I make it persist as l ...

jQuery Form Plugin - fails to trigger error callback for Internal Server errors (500)

I am dealing with a situation where my server is returning a Status code 500, but my jQuery Form is triggering the success callback instead of the error callback. My current jQuery version is 1.7.1 and jQuery Form version is 2.73 from March 2011. The serv ...

Learn how to implement scrolling text using JavaScript and jQuery, where text slides by clicking on the previous and next icons

click here to see the image Is it possible to create a text slider that moves when clicking on previous and next icons? I want only 10 texts to be visible at a time, with the rest hidden. When clicked, all the texts should appear. Unfortunately, I don&apo ...

Tips on transmitting checkbox data from AJAX to PHP

I'm currently working with this code and facing an issue where data from checkboxes is being sent to PHP one by one. I want to be able to send multiple selected data at once. How can I modify the code to achieve this? $('#lunas').click(funct ...

Maximizing Angular and Require's Potential with r.js

I'm facing some challenges while setting up r.js with require in my Angular application. As I am new to AMD, solving this issue might be a simple task for someone experienced. However, I need to maintain the current directory structure as it allows me ...

Exploring the perfect blend of ReactJs Router Links with material-ui components, such as buttons

I am currently facing a challenge in integrating the functionality of react router with material ui components. For example, I have a scenario where I want to combine a router and a button. I attempted to merge them together and customize their style. In ...

The search results from the autocomplete feature of the Spotify API appear to be missing

Exploring the Spotify API - I am attempting to implement an autocompletion feature using jQuery for a field that suggests artists as users type. Here is what I have so far: HTML: <input type="text" class="text-box" placeholder="Enter Artist" id="artis ...

Assign a value to ng-model using JavaScript

Encountering an issue while working with JavaScript in AngularJS. There is a text field identified by id="longitude". <input type="text" data-ng-model="newwarehouse.longtitude" id="longitude"/> The value of this field is being set using JavaScript. ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...