How can I transform an array of text into dropdown options?

Currently, while utilizing Vue and vue-bootstrap, I am facing the task of populating a dropdown menu with an array of text items retrieved from my database. The <b-form-select> component in Bootstrap requires objects of the form

{value: 'some value', text: 'displayed text'}
.

The format of my original array is ['item1', 'item2', 'item3'].

I am wondering if there is a more efficient method to transform my array into dropdown-friendly objects instead of using a repetitive forEach loop to manually create each object every time. Currently, my code looks like this:

formatEventTypes() {
  this.eventTypes = [];
  this.rawEventTypes.forEach(rawType => {
    this.eventTypes.push({value: rawType, text: rawType});
  });
}

While this approach works for now, it is not optimal especially when dealing with multiple dropdowns.

Any suggestions or insights would be greatly appreciated!

Answer №1

After examining the code snippet, I noticed that 'this.eventTypes' is assigned a new value based on 'this.rawEventTypes'. The value is transformed using the map function to create an array of objects with 'value' and 'text' properties.

What perplexes me is how 'rawType.type' would function correctly if the input array is structured like

['item1', 'item2', 'item3']

Instead of,

[{ type: 'item1' }, { type: 'item2' }, { type: 'item3' }]

Answer №2

A function can be defined like the one shown below for easy reuse multiple times:

//itemsList represents an array of strings
//e.g., ['apple', 'banana', 'orange']
function createDropdownList(itemsList) {
  var dropdownList = [];
  itemsList.forEach(item => {
    dropdownList.push({value: item, label: item});
  });
  return dropdownList;
}

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

Remove any errors as soon as the input field becomes valid

My current setup involves AngularJS with node.js. To handle errors, I have devised the following strategy: node router effect.js: router.post('/', function(req, res, next){ req.checkBody('name', 'Eff ...

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

Optimal Strategies for Handling Slugs with Laravel and Vue Router

I am working on a Laravel and Vue application. Specifically, I have developed a single-page application using Vue for a section called "shop". Within this shop, there are 3 subpages: "about", "products", and "contact". In my routes.php file: Route::get(& ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

Having issues with my JavaScript code - it just won't function

I am having an issue with my JavaScript code. I don't receive any errors, but when I click the submit button, nothing happens. I have followed a video tutorial and watched it twice, but I can't seem to figure out what is wrong here. Here is the ...

Unraveling an AJAX response in JSON format using jQuery

I am a beginner in the world of Jquery and Ajax. I've crafted the code below to automatically populate a form with data after selecting an option from a combo box within a form, using guidance from this helpful post Autopopulate form based on selected ...

Arranging elements in an array based on two different properties

Trying to organize an array of elements (orders details). https://i.stack.imgur.com/T2DQe.png [{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":&qu ...

What is the process for attaching an iterator to the name value of every element within a cloneNode?

Consider the following scenario: <div id="addNewMenuElementPart2"> Numerous elements with a name attribute are present here. </div> <div id="addNewMenuElementPart3Optional"></div> Additionally, t ...

A large canvas displaying a single optimized image

Hello, I have a large image on the canvas that measures around 10,000 pixels by 10,000 pixels. I am looking for zoom in/out functionality. Can you recommend what technology I should use? Should I consider splitting the image into smaller segments like Go ...

Quasar: Drawer now switches to Mini-mode automatically

Currently, I am using Quasar and I want the drawer to automatically switch to mini mode when users resize their browser window to make it smaller. At the moment, the drawer always remains open even when I narrow the browser width. Below is what I have tri ...

Spin the object around the z-axis, with the point serving as the center of rotation

I have a unique challenge with positioning a HUD object on the front of a tube in Three.js. The HUD needs to align itself based on a vector point, always facing towards the high side of that point, regardless of the direction and position of the tube. To b ...

Spring's $.getJSON failing to trigger callback functions

After conducting extensive research, I have come across many similar issues but nothing that has provided a solution to my problem. I am facing an issue where my getJSON call is successfully calling my Spring controller and receiving JSON data in response ...

Issue with selecting multiple items in DataTables using the shift key

Currently, I am working with datatable 1.10 and have successfully created a table. However, I am unable to enable the multiple "shift select" functionality for its rows. Referring to the official DataTables documentation: The TableTools plugin offers fou ...

if else within the <dd></dd> tags

I have a code snippet in Vue.js that displays a certain value. <dl> <!-- Fan speed --> <dt>{{ $t('pageInventory.table.fanSpeed') }}:</dt> <dd>{{ dataForma ...

Adding a new value to an array of objects without altering the existing values in ReactJS and NextJS

I have a JSON file containing image names that I need to organize into a Key-Value Object. I am currently using regex to create keys by removing "-img[image No]". However, I am having trouble storing all the image names in the array without overwriting pre ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

I'm looking for a solution to reorganize my current state in order to display the image URL

My React component, which also utilizes TypeScript, is responsible for returning a photo to its parent component: import React, { useEffect, useState } from "react"; import axios from "axios"; export const Photo = () => { const [i ...

Gulp- Ensuring the latest versions of your javascript files

I have implemented bundling and minification for my JavaScript files using gulp. What I am aiming to achieve is that whenever I make a change in any of my files and run gulp, a new bundled and minified file with a version number is generated. For example: ...

I keep encountering an attach() error every time I try to close a modal that contains a vee-validated form

Every time I try to close a bootstrap modal (using bootstrap-vue) that includes a vee-validated "update" form with vue.js, I encounter the following error: main.js:477686 Uncaught (in promise) Error: [vee-validate] Validating a non-existent field: "#35". ...

Fading away backdrop images for the header

I've created a header class in my CSS with the following styling- header { background-image: url('../img/header-bg.jpg'); background-repeat: none; background-attachment: scroll; background-position: center center; .backg ...