Looping through Vue with multiple options

Looking for help with Vue2 looping to display multiple options within a select element.

We have an object structured like this;

sorting = {
    name: [
        'asc',
        'desc'
    ],
    price: [
        'cheapest',
        'expensive'
    ]
}

How can we set up the loop to achieve the desired output below?

<select>
    <option value="name:asc">name asc</option>
    <option value="name:desc">name desc</option>
    <option value="price:cheapest">price cheapest</option>
    <option value="price:expensive">price expensive</option>
</select>

Struggling to figure out how to include the second option listed above;

<select id="sortBy" class="form-control pr-3" v-model="sortBy">
    <option
        v-for="(options, sort) in sorting" :key="`${sort}`"
        v-bind:value="`${sort}:${options[0]}`"
    >
        {{ sort }} {{ options[0] }}
    </option>
</select>

Answer №1

One reason for this issue is that your sorting data includes nested arrays. To address this, you need to iterate through each key (which you've already done) and then iterate through the array within each key to create the options.

Instead of dealing with this complexity directly in the template, which can make it less readable, my suggestion is to create a computed property that handles the option generation for you.

A simple approach would be to use Object.entries() to get a tuple of key and value, then iterate through the value to return the key:arrayValue combination. You can use Array.prototype.flatMap to flatten the resulting array:

new Vue({
  el: '#app',
  data: {
    sorting: {
      name: [
        'asc',
        'desc'
      ],
      price: [
        'cheapest',
        'expensive'
      ]
    },
    sortBy: '',
  },
  computed: {
    options() {
      return Object.entries(this.sorting).flatMap(([key, optionsByKey]) => {
        return optionsByKey.map(v => `${key}:${v}`);
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select id="sortBy" class="form-control pr-3" v-model="sortBy">
    <option v-for="(option, i) in options" :key="i" :value="option">
      {{ option.replace(':', ' ') }}
    </option>
  </select>
  <br /><br />
  Selected value: {{ sortBy }}
</div>

Answer №2

Utilize a dual option loop setup.

<select id="sortBy" class="form-control pr-3" v-model="sortBy">
    <option
        v-for="n in options.name" :key="`name:${n}`"
        :value="`name:${n}`"
    >
        name {{ n }}
    </option>
    <option
        v-for="p in options.price" :key="`price:${p}`"
        :value="`price:${p}`"
    >
        price {{ p }}
    </option>
</select>

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

Featuring data utilizing Ajax JSON in CodeIgniter

How can I display the data using AJAX? After making the data call to the controller, the JSON data is available but the data for "name", "address", and "telp" based on the "id_data" is not showing up. How can I display this data? Views <input id="id_d ...

The Cordova minification tool fails to compress files within the browser platform

I recently installed the cordova-minify plugin to compress the javascript code in my Cordova app. When I tried running the command: cordova build browser An output message appears: cordova-minify STARTING - minifying your js, css, html, and images. ...

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

Tips for positioning the cursor at the beginning of text and shifting the focus to the start while utilizing the MaterialUI Input component

I have scoured various online forums for a solution to this issue, but none of the suggestions seem to work. Although I managed to position the cursor at the beginning of the text, it did not shift the focus accordingly. Here is the code snippet for the co ...

If I dared to eliminate the emphasized line, this code would completely fall apart

<!DOCTYPE html> <html> <head> </head> <body> <h1 id="message-el">Ready to play?</h1> <p id="cards-el"></p> <p id="sum-el"></p> <butto ...

Creating a Border Length Animation Effect for Button Hover in Material-UI

I'm currently exploring Material-UI and trying to customize a component. My goal is to add a 'Border Length Animation' effect when hovering over the button. Unfortunately, I have yet to successfully implement this animation as intended. For ...

The color of the last clicked DIV is supposed to stay permanent, but for some unknown reason

I'm attempting to replicate this design in my project: http://jsfiddle.net/AYRh6/26/ However, I am facing issues with it and cannot pinpoint the exact problem in the code. I am using code for a toggle effect. Any assistance would be greatly appreciat ...

why is my angular listing malfunctioning when I try to compare two fields?

<div ng-controller="SamsungServicesCtrl"> <ion-content> <li class="item item-checkbox" ng-repeat="item in items" > <img src="{{item.icon}}" style="float:left;height:30px;width:30px;padding-right:5px;" & ...

In JavaScript, the function yields a proxy rather than an object

Let's say I have an array: const arr = ['one', 'two', 'three'] Now, imagine I have a function that is designed to take an array of strings and return an array of objects: const func = (arr) => arr.map(item => ({str ...

AngularJS is experiencing delays when processing subsequent $http delete requests, leaving them stuck in a

I am currently working on a project where I have a table displaying a list of objects, with each object having multiple child objects associated with it. The technologies I am using include Angular 1.2.20, Express 4.6.1, and Node 0.10.25. In the table, the ...

What is the best way to transfer a value from a function to a variable in VueJs?

Currently, I am receiving the base64 of an image URL. When passing the getImage function to the savepdf function and attempting to store the callback function's base64_data in a variable, an error is thrown: An error occurs - Cannot set property &a ...

MongoDB results are being pushed into an array, yet the array continues to stay devoid of any data

Hello all! This is my introductory question on stack overflow, so I appreciate your patience. I am currently working on a controller function that is responsible for rendering the Google Maps API. My goal is to iterate through the results fetched from Mon ...

How can I create a fading trail effect in Three.js that diminishes over time?

I am interested in achieving a similar effect to the example I found on this website: However, my goal is to have the old trail gradually fade into the background over time instead of cluttering the screen with persistent marks. I discovered that by usin ...

Utilizing Vuex for Efficient Management of Forms with Ever-Changing Data

My goal is to implement a filtering mechanism that can handle dynamically loaded filtering values. For example, receiving data in the form: [ { key : value }, { key : value } ] Then, in my template: <md-checkbox @change="change($ ...

What could be causing the invalid expression error to pop up in my Vue.js template?

I encountered an error within my vue single file component: Errors compiling template: invalid expression: Unexpected token { in {{ jobs[0].build_link }} Raw expression: v-bind:href="{{ jobs[0].build_link }}" The complete code causing the is ...

Tips for utilizing Vue-CLI-service to serve content over HTTP-2

Is there a way to configure Vue-CLI-service to serve on HTTP-2 instead of the default HTTP 1.1? ...

Is the JSON response in the AJAX request accurate, even though the content is not being refreshed?

I have a function that is triggered in the following manner: success: function(json) { if(json.valid == 1) { // Another show/hide operation that functions properly $("#div-response-" + id).html(json.message); } ...

Having an issue with HTML and JavaScript where the button won't open when pressed. Any help is appreciated

https://jsbin.com/haluhifuqe/edit?html,js,output I'm facing an issue with my HTML & JavaScript code - when I click the button, it doesn't open. Can anyone help me out? <!DOCTYPE html> <html> <head> <meta charset="utf-8 ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...