Displaying an element as a dropdown menu on PrimeVue

I have a challenge with rendering a Dropdown using PrimeVue with the given script:

<template lang="pug">
Dropdown#tag(v-model="tag" :options="tags")
</template>

<script setup>
import axios from 'axios'
import { ref, onMounted } from 'vue'

const tag = ref()
const tags = ref([])

onMounted(() => {
  tags.value = []

  Promise.all([
    axios.get('/api/v1/tags')
// ... some more requests here
  ]).then(([respTags]) => {
    tags.value = respTags.data
  }).catch($error => {
    toast.add({ severity: 'error', detail: $error, life: 3000 });
  }).finally(() => {
    isLoading.value = false
  })
})

</script>

The issue arises because respTags is in the form of an object like

{tag1: {version: "1.2.3"}, tag2: {version: "1.2.4"}}
. When passing it to the dropdown, I receive an error message
[Vue warn]: Invalid prop: type check failed for prop "options". Expected Array, got Object
.

My objective is to use the object keys (tag1, tag2...) as values and the corresponding version as labels.

I understand that this can be achieved using a loop, but I am exploring if there are alternative approaches to avoid implementing a separate loop specifically for this task.

Answer №1

Prefer Arrays over Objects

[Vue warn]: Invalid prop: type check failed for prop "options". Expected Array, got Object

The error message is straightforward. You are providing an object when an array is expected. Make sure to pass an array instead.

const objectFromApiResult = respTags.data // {tag1: {version: "1.2.3"}, tag2: {version: "1.2.4"}}
tags.value = Object.keys(objectFromApiResult).map((key) => ({
  value: key,
  label: objectFromApiResult[key].version
})) // [{label: "1.2.3", value: "tag1"}, {label: "1.2.4", value: "tag2"}]

In the code snippet above, I utilize Object.keys() to transform the keys of your object into an array. Subsequently, each element undergoes manipulation using .map, where I replace the string-type key name with an object containing label and value properties.

Object.keys() - MDN Documentation
Array.property.map() - MDN Documentation
Dropdown - props.options - PrimeVue Documentation (required, type array)

An array of selectitems to display as the available options.


Customizing Label and Value Properties

You can specify the column names for the label and value variables within the object present in the array. Use the props.optionLabel property for the label's column name and props.optionValue for the value's column name.

<Dropdown v-model="tag" :options="tags" optionLabel="name" optionValue="version" />
const objectFromApiResult = respTags.data // {tag1: {version: "1.2.3"}, tag2: {version: "1.2.4"}}
tags.value = Object.keys(objectFromApiResult).map((key) => ({
  version: objectFromApiResult[key].version,
  name: `Version: ${objectFromApiResult[key].version}, TagKey: ${key}`
})) // [{version: "1.2.3", name: "Version: 1.2.3, TagKey: tag1"}, {version: "1.2.4", name: "Version: 1.2.4, TagKey: tag2"}]

Dropdown - props.optionLabel - PrimeVue Documentation - (optional, type string, default: label)
Dropdown - props.optionValue - PrimeVue Documentation - (optional, type string, default: value)


Utilizing a Single Property for Label and Value

You can also derive the label and value from a single property.

<Dropdown v-model="tag" :options="tags" optionLabel="version" optionValue="version" />
const objectFromApiResult = respTags.data // {tag1: {version: "1.2.3"}, tag2: {version: "1.2.4"}}
tags.value = Object.keys(objectFromApiResult).map((key) => ({
  version: objectFromApiResult[key].version,
})) // [{version: "1.2.3"}, {version: "1.2.4"}]

Converting Object Values into an Array

In scenarios like this, utilizing the Object.values function is more appropriate than Object.keys.

<Dropdown v-model="tag" :options="tags" optionLabel="version" optionValue="version" />
const objectFromApiResult = respTags.data // {tag1: {version: "1.2.3"}, tag2: {version: "1.2.4"}}
tags.value = Object.values(objectFromApiResult) // [{version: "1.2.3"}, {version: "1.2.4"}]

Object.values() - MDN Documentation

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

Guide on importing table information into an array using jQuery

I am facing an issue where I want to extract values from a dynamically generated table and then send those values in an AJAX call. The problem is that even though I am able to increase the number of rows in the table dynamically, when I try to capture the ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

Sorting a 2D array in Javascript based on numerical values

I've come across a few similar posts regarding this issue, but none have provided solutions that work for my specific situation. I'm feeling lost on how to solve this problem (like Sort a 2D array by the second value) Let me explain the challeng ...

JavaScript code to output CSS styled text: "echo"

Implementing anti-adblock on my site was necessary, as my bitcoin faucet relies on ads to function. I wrote some code to detect adblock on the client's browser: function TestPage() { if ($('.advertisement').height() == 0) var advertisement ...

Error: Unable to locate the reference

Having trouble with my JavaScript code not recognizing the linked .js files I added. I initially linked them through CodePen, but manual references don't seem to be working. Attempted suggestions from this page Why does jQuery or a DOM method such as ...

A guide on implementing the IF statement to prevent the Weather API fetch from crashing when the user inputs an incorrect city name

Explaining The Issue - Objectives of the Task Creating a weather application that displays data from the OpenWeather API on the screen. - Current and Desired Outcomes Regardless of whether the user enters a valid city name or leaves the field blank, n ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...

Revamping the login interface for enhanced user

Whenever I attempt to login by clicking the login button, there seems to be an issue as it does not redirect me to any other page. Instead, I am left on the same page where I initially clicked the button. The intended behavior is for users to be redirected ...

Plotting Data Points with Tags in React Native

After doing some research, I came across a few React Native packages that offer scatter plots such as react-native-scatter-chart, react-native-chart-kit, and react-native-chartjs. However, I am interested in finding something more customizable. I'm s ...

Lost in a strange predicament

As I try to send props from my parent component to the child component, I am facing an issue where one of the children within the coin prop seems to be lost when I receive the props in componentWillReceiveProps(). This discrepancy becomes evident through t ...

Don't forget to expand or collapse

I'm struggling to make this work. My goal is to initially display 50 characters and show the rest when the "read more" button is clicked, and vice versa with "read less." Another problem I've noticed is that when I click the back browser button, ...

Nested loops in JavaScript can be combined with promises to efficiently handle

I am facing a challenge in looping through an array that contains another array as one of the parameters. My goal is to iterate through this nested array according to specific requirements, and then execute a function once the parent loop is finished. Can ...

Why is my showMap() function not executing when the button is clicked? How can I resolve this issue in JavaScript?

Why isn't the JavaScript code for showMap() running? How can this issue be resolved? <html> <title></title> <script> function showMap() { alert("rong"); } fun ...

Caution: Discrepancy found in Prop className between server and client rendering in a React SSR application

Currently, I am working on integrating a collapsible sidebar into my React application that relies on a value stored in the local storage. The intended behavior is for the sidebar to have the className of "inline" if the value is true, and "hidden" if the ...

The transmission of information through Ajax is encountering a problem as the data is not properly

Having some trouble using Ajax to send form data and echoing it on the PHP page. Since I'm new to Ajax, I might have made a mistake somewhere in my code. Below is what I currently have: $(function () { $('form').on('submit&apos ...

Blender Mesh Not Visible in Three.js

After creating a mesh in Blender, I attempted to use it in three.js. Although the file is being loaded according to the event log, all I see is a black screen. How can I ensure that the mesh actually appears on the screen? import * as THREE from 'thre ...

What is the method by which the asynchronous function produces the ultimate output?

Is there a way to modify a Dojo framework-created class with an asynchronous method so that it only returns the final value instead of a Promise or any other type? ...

What is a way to retain the value of a variable after a request, while starting off with a different value on the initial load?

In my Flask application, users have the option to choose a specific time period with a start date and an end date. When the page initially loads, I want the start date to default to the first day of the current month and the end date to be the current day. ...

Connect user input to a predefined value within an object

I am currently working on developing a timesheet application that allows users to input the number of hours they work daily. The user data is stored in an object, and I aim to display each user's hours (duration) in an input field within a table. An i ...