Search code examples
javascriptvue.jsvuejs2vue-componentvue-multiselect

Vue-multiselect: How to convert object to array for use in options prop?


I am using vue-multiselect like so:

    <multiselect
      id="customer_last_name_input"
      v-model="value"
      :options="activeUserProfiles"
      label="lastname"
      placeholder="Select or search for an existing customer"
      track-by="uid"
      :close-on-select="true"
      @select="onSelect"
      @remove="onRemove"
      :loading="isLoading"
      :custom-label="customerSelectName"
      aria-describedby="searchHelpBlock"
      selectLabel=""
    >

...that grabs the list of active customers from an Array and then makes them available in a nice select menu.

This works good. However, I need to add another option from another resource (called customerNone) to the options prop and but the data is returned as an Object like so:

{"uid":1,"lastname":"None Given","firstname":"User","email":null,"phone":null...blah}

The vue-multiselect docs state that the :option prop MUST be an Array.

Question: What is the best way for me to handle this in the vue-multiselect component? Here's my attempt to help explain what I am trying to do (not sure if this is the best way to handle it). Unfortunately, my attempt causes a console error (see below):

I am passing a prop down called noCustomer which, if is true, I need to use customerNone profile on :options:

<multiselect
      :options="noCustomer ? customerNone : getActiveUserProfiles"
>

here's the error:

Invalid prop: type check failed for prop "options". Expected Array, got Object 

Is there a way I can convert the customerNone object to an array of object? Thanks!


Solution

  • You could wrap the customerNone object in brackets at the time that you pass it to the <multiselect> like [customerNone].

    This syntax creates a new array on the fly, having 1 element that is the object variable:

    <multiselect
      :options="noCustomer ? [customerNone] : getActiveUserProfiles"
    >
    

    Update for comments

    In order to auto-select the generic option when it's available, use a watch on the noCustomer prop to set value whenever noCustomer === true:

    watch: {
      noCustomer(newValue, oldValue) {
        if(newValue) {        // Checking that `noCustomer === true` 
          this.value = this.customerNone;
        }
      }
    }