Iterating through a collection of items in Vue.js using the v

I am attempting to cycle through an object using v-for.

exampleObject =[a,b,c,d]
Requirement = display only a if it exists in exampleObject, otherwise show b, c, d.
<div v-if="checklist.types">
      <div v-for="type in checklist.types">
         <div v-if="type.Name == 'Module1'">
              show module 1
         </div>
         <div v-else>
             <span>{{type.Name }}</span>
         </div>
     </div>
</div>

The above code displays all values because the condition is checked within the For Loop. Is there a way to iterate and check the object beforehand?

Answer №1

To efficiently handle the data, you can create a computed property that generates an array containing...

  1. Only a / Module1 if it is available
  2. The entire exampleObject / checklist.types otherwise

This computed property can then be easily iterated through.

export default {
  data: () => ({
    checklist: {
      types: [/* whatever */]
    }
  }),
  computed: {
    modules: ({ checklist: { types } }) => {
      const module1 = types.find(({ Name }) => Name === "Module1")
      return module1 ? [module1] : types
    }
  }
}
<div v-for="module in modules" :key="module.Name">
  <span>{{ module.Name }}</span>
</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

Customizing ESLint configurations for a more productive local development environment

Let's consider an inspiring scenario: I am in the process of coding and need to troubleshoot an issue, so here is a snippet of my code: function foo() { console.log("I'm resorting to printf debugging in 2016"); } However, our build setup in ...

Scripting issues detected in Safari and Microsoft Edge browsers

I recently finished developing an AngularJs Application that works flawlessly on Google Chrome and Mozilla Firefox. However, upon testing it on Safari and IE-11, I encountered errors in the console. One particular piece of code that causes issues is used ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Basic JavaScript framework centered around the Document Object Model (DOM) with a module structure similar to jQuery. Currently facing challenges with

In order to create a simple framework with jQuery style, I have written the following code: (function(window) { window.smp=function smpSelector(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; if (!s ...

Using React to update an existing array of objects with a new array containing objects of the same type

My issue involves an array in a class's state, referred to as A. A is populated with objects of type B through the function f in the constructor. Subsequently, I create a new array of objects of type B called C using f and new data. Upon setting the s ...

Chrome's XPath attribute selection is not functioning properly

After running a small test with expect.js, here are the results: describe('xpath', function () { it('locates attribute nodes', function () { $(document.body).append('<string fooBar="bar"><data id="xyz">< ...

I am encountering an issue stating "indexRouter has not been defined"

Encountering an error "indexRouter is not defined" while attempting to run the code below. Despite attempts to remove the line, additional errors persist. Can anyone clarify the rationale behind using the common variable router for both index.js and user.j ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

PHP's for loop may not iterate through the entire array

I am currently using PHP/7.2.0beta3 and I have a requirement to develop a custom function in PHP that can reverse an array. For example, if the array is (1,2,3), the desired outcome should be (3,2,1). My initial approach was to utilize the array_pop funct ...

There seems to be a problem with the output when trying to display the message "You said ${reply}"

In the following code snippet, vanilla.js is being used with ATOM as the text editor and running on nodejs via terminal: 'use strict'; const Readline = require('readline'); const rl = Readline.createInterface({ input:process.stdin, ...

The PHP script is not being activated by AJAX

I am completely baffled by the situation at hand. Sometimes, I open a different browser to test my changes and it works as expected. But then, when I try again, it fails. It's driving me crazy. On syllableapp.com, I set up a MySQL database that I can ...

I am looking to implement custom styles to a navigation bar element upon clicking it

When I attempted to use useState(false), it ended up applying the styles to all the other elements in the navbar. import React, { useState } from 'react'; import { AiOutlineMenu } from 'react-icons/ai'; import { Navbar, NavContainer, Na ...

Pinia throws a useStore is not callable error

I have been trying to resolve the issue with (0 , pinia__WEBPACK_IMPORTED_MODULE_1__.useStore) is not a function but unfortunately, I haven't been able to find a solution. Can anyone point out what mistake I am making? Here is my store.js code: im ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Utilize Vue.js to transmit HTTP requests with specified headers and parameters

I'm trying to figure out how to create a LinkedIn login component, but I'm having trouble finding information about headers and parameters. Can someone help me understand how to send a GET or POST request with parameters and headers? Here's ...

"Troubleshooting VueJS: Issue with default value not being set in

Trying to set a default value for a select in Vue. <script src="https://unpkg.com/vue"></script> <div id="app"> <select v:model="select"> <option value="1">1</option> <option value="2">2</optio ...

Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters. Initially, the component was u ...

The pagination feature for Swiper is experiencing issues across both desktop and mobile platforms

I am having an issue with the pagination display in the text. I would like it to appear below the text as a standalone item for better visibility. Another problem arises when viewing the page on mobile devices - the hamburger menu displays behind the slid ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...