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