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

Checking for an existing alert in JavaScript

In my development of a Blackberry Webworks (HTML5) app, I am running multiple methods simultaneously in the background. If any of these methods happen to fail, an alert is triggered using the alert() method in JavaScript. However, if both methods fail, two ...

terminate a node-cron task or abort a node-scheduler job

I'm currently working on a nodejs project that involves managing multiple cron jobs. However, I've encountered an issue when attempting to cancel these jobs. Here's the scenario: I have set up several cron jobs using node-cron or node-sch ...

Tips for showing various column information as tooltips in ag grid's pivot mode

var ColumnDefinitions = [{ headerName: "Column A", field: 'colA', rowGroup: true }, { headerName: "Column B", field: 'colB', pivot: true, enablePivot: true }, { headerName: "Column C", field: ...

Modifying certain elements in a text to emphasize (PHP)

Running JavaScript code smoothly is not a problem for me, but unfortunately, I am facing difficulties when it comes to PHP. I wish to change certain words in the text for emphasis. How can I achieve this? var terms = 'term1#term2#term3'; ...

Acquire feedback from PHP using SweetAlert notifications

I need to update my HTML form to function like this: <script> function getName() { var name = $('#name').val(); var url_send = 'send.php'; $.ajax({ url: url_send, data: 'name=' + name, ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

Tips for passing navigator reference to React Native's <Drawer/> component?

Utilizing react-native-drawer ( https://github.com/root-two/react-native-drawer ) in my index.ios.js file, I have the following setup where I am attempting to pass the 'navigator' reference into the <DrawerPanel /> of <Drawer /> compo ...

Dynamic Changes in Vue Router Parameter Object Upon Navigating Back in Browser

When I navigate to a route in Vue.js using vue-router, I pass an Object parameter called forum. { path: '/forum/:forum', name: 'ForumView', component: ForumView, props: true } If I leave the forum route and then try ...

Is it possible to dynamically modify the role in a migration table between admin and user in Laravel-8 based on user selection?

After developing a users table without a role column, I realized the need to add a role column in my migration table. This role column should contain either "admin" or "user" based on the selection made by the registered person on the frontend UI page. If ...

Ways to showcase the outcome of a spin after each rotation

I am currently working on a spinning code snippet that allows users to spin and potentially win different amounts. The code includes functionality to prevent more than 3 spins, set random rotation values, and animate the spinning effect. However, I now wa ...

Ensure to verify the dimensions and size of the image prior to uploading

Is there a way to check the dimensions of an image using this function? I want to verify it before uploading... $("#LINK_UPLOAD_PHOTO").submit(function () { var form = $(this); form.ajaxSubmit({ url: SITE_URL + 'functions/_app/execute ...

"Utilizing d3 to parse and track variables within JSON data

To calculate the number of occurrences of s1, s2, and s0 in JSON data and use this information to plot a multiline chart with date (path of date is as follows reviews_details>>variable vf of JSON) on the X-axis versus the number of reviews (s1/s0/s2 ...

Is the order of execution of extraReducers before or after the reducers?

I was curious about the createSlice function in redux-toolkit and how it handles the order of execution for extraReducers compared to reducers. Can we determine if the extraReducers are executed before or after the reducers, or is the order indeterminate? ...

retrieve all entries from a paginated grid

Currently, I am utilizing the datatable feature in bootstrap4 with a table that has pagination set to display 10 items per page. I have implemented a function to retrieve values from the table, however I am facing an issue where I am only able to retriev ...

I'm running into an InvalidSelectorError and I could use some assistance in properly defining

As I gaze upon a massive dom tree, my task using NodeJS/Selenium is to locate an element by the title attribute within an anchor tag and then click on the associated href. Despite being a newcomer to regex, I am encountering numerous errors already. Below ...

Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this: [ {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"origin ...

JavaScript forEach functionality is not compatible with Dynamics CRM 2016

I'm currently working on writing some JavaScript code for a ribbon button in Dynamics CRM 2016 that will extract phone numbers from a list of Leads displayed in the Active Leads window. However, I've encountered an error message when attempting ...

What is causing the recurring failure of file input changes to take effect?

Here is the code snippet I'm working with: <input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" /> Along with the handler function: public onFileSelected(e: Fi ...

Utilizing material-ui textfield involves a delay when the input is being focused

Is there a way to trigger inputRef.current.focus() without relying on setTimeout? It seems like the focus is not working as expected in React or MaterialUI. For a demonstration, visit: https://codesandbox.io/s/goofy-gareth-lkmq3?file=/src/App.js export de ...

Why are my Bootstrap nav-tabs not showing tab-content in MVC?

I'm dynamically creating tab navigation from controllers using a list. <div class=""row> <div class="col-xl-3"> <!-- Tabs nav --> <div class="nav flex-column nav-pills nav-pills-custom" id="v-p ...