Extract the value from an input-select in VueJS instead of the key

Here is the input-select code snippet:

<input-select v-model="county" id="county" :options="getCountyList()">
  &dagger; County
</input-select>

The function getCountyList() is defined as follows:

getCountyList: function () {
  var retarr = [];
  for (let i = 0; i < json.length; i++) {
    if (json[i].state_id == this.state) {
      // here STATE selected in previous drop down,
      // match it with state from json and get COUNTY
      retarr[i] = json[i].county_name;
    }
  }
  const mySet = new Set(retarr); //remove duplicates and get DISTINCT County list
  console.log("this is mySet COUNTY return array :", mySet);
  return mySet;
};

The output of

console.log ("this is mySet COUNTY return array :",mySet )
is as follows:

0: undefined
1: "St. Clair"
2: "Jefferson"
3: "Shelby"
4: "Tallapoosa"
5: "Blount"
6: "Talladega"
7: "Marshall"
8: "Cullman"
9: "Bibb"
10: "Chilton"
11: "Walker"

However, the issue faced is that v-model="county" is receiving keys like 1, 2, 3 instead of the actual COUNTY Name upon selection. How can this be resolved?

Answer №1

Here is a potential solution:

fetchCountyList: function(){
   var counties=[]; 
      for (let i=0; i< data.length; i++){
        if (data[i].stateCode == this.selectedState ) { // Consider the state selected in the previous dropdown, 
and find matching counties from the dataset
               counties[i] = {name: data[i].countyName, code: data[i].countyCode};
            }
      }
    

      return counties;
  
}

No need to worry about duplicates when using objects.

Answer №2

Here is a neat way to filter and retrieve the selected option from the select field in vuejs.

Key points:

  1. Utilize computed properties for filtering out or modifying reactive properties in vue
  2. Consider using lodash to remove duplicates from arrays. It offers various methods for array manipulation without the need for writing complex logic.
  3. Avoid manually looping over an array, creating another array, and then using Set to filter it. This method is unnecessarily long-winded.
  4. You can attach the entire item object as the option's value and access its properties later, as demonstrated below.
  5. Follow the camelCase naming convention for variables in vue.
  6. Adhere to the new ES6 standards by utilizing const and let.
P.S: Expand the snippet below and run it!

new Vue({
  el: "#app",
  data() {
    return {
      country: '',
      json: [
        { stateId: 1, countryName: "St. Clair" },
        { stateId: 2, countryName: "Jefferson" },
        { stateId: 3, countryName: "Shelby" },
        { stateId: 4, countryName: "Tallapoosa" },
        { stateId: 5, countryName: "Blount" },
        { stateId: 6, countryName: "Talladega" },
        { stateId: 7, countryName: "Marshall" },
        { stateId: 8, countryName: "Cullman" },
        { stateId: 9, countryName: "Bibb" },
        { stateId: 10, countryName: "Chilton" },
        { stateId: 11, countryName: "Walker" },
        { stateId: 1, countryName: "St. Clair" }
      ]
    };
  },
  computed: {
    countries() {
      return _.uniqBy(this.json, "countryName");
    },
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7073787d6f745c">[email protected]</a>/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<template>
  <div>
    <select v-model="country" id="county">
      <option
        v-for="item in countries"
        :key="item.stateId"
        v-bind:value="item"
      >
        {{ item.countryName }}
      </option>
    </select>

    <span>Selected Country: ID: {{country.stateId}} Name: {{ country.countryName }}</span>
  </div>
</template>
</div>

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 to recursively iterating through an array of objects in TypeScript/Javascript

In my current programming challenge, I am dealing with an array of objects that have two properties: target and source. Additionally, there is a designated starting source to begin with. The goal is to start from the starting source and recursively find a ...

Backbone - First render client views before creating them upon saving

I'm completely stumped on how to make this work. I can successfully create the models, but running create or anything else on them afterwards seems impossible. It's been 6 long hours of trying and failing... Can someone please point out where I&a ...

Displaying PHP output within a JavaScript expression

Let's dive into a scenario involving a basic HTML document and some JavaScript that's loaded within it: <!-- doc.html --> <!doctype html> <html lang="en"> <head> <script type="text/javascript" src=" ...

Showing loading spinner when clicked

I created a spinning animation in CSS, but now I want to hide it and only display it when a button is clicked. I've tried to achieve this using the following code, but the spinner doesn't appear when I click the submit button. To hide the spinne ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

Struggles encountered while configuring React

I'm in need of assistance with setting up React, even though I have both Node and npm installed. When I enter the following command: npx create-react-app new-test-react --use-npm I encounter the following error message: npm ERR! code ENOTFOUND npm E ...

The NodeJS module 'request' is producing symbols instead of expected HTML content

Currently, I am delving into the world of Nodejs and experimenting with web scraping using node.js. My tools of choice are the node modules request and cheerio. However, when I attempt to request a URL, instead of receiving the HTML body, I get strange s ...

Modify the website link for the ajax request

I have been successfully fetching data from a URL link using curl, but I have encountered an issue. The response data includes ajax calls that are using my server domain instead of the original path where the files are located. For example: /ajax/fetch.ph ...

Is the layout optimized for mobile devices?

I am attempting to design a mobile-friendly layout using CSS and HTLM5. In my styles, I have included the following code at the end: @media only screen and (max-width: 480px) { body { padding: 5px; background-color:#FFF; back ...

Update data dynamically on a div element using AngularJS controller and ng-repeat

I am currently navigating my way through Angular JS and expanding my knowledge on it. I have a div set up to load data from a JSON file upon startup using a controller with the following code, but now I am looking to refresh it whenever the JSON object cha ...

JavaScript code that transforms a comma-separated string of words into key-value pairs within an array

I am looking to transform a list of email addresses into a key-value object within an array. Starting with "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40252d21292c002d21292c6e232f2d">[email protected]</a> ...

Tips for incorporating additional items into an established useState array utilizing map() or foreach()?

I'm working on developing a social media platform similar to Twitter, and I'm facing challenges with the news feed functionality. Essentially, the news feed is supposed to fetch tweets from my firebase database for each user followed by the curre ...

What is the correct way to change the v-model value of a child component within a parent component

Currently, I am in the process of mastering Vue.js and I have a specific goal. I want to modify the binding value of the child component's v-model and then trigger an event in the parent component. As I delve into the Element UI documentation, I aim ...

What is the best way to loop through an object in TypeScript and replace a string value with its corresponding number?

My situation involves handling data from a 3rd party API that consists of multiple properties, all stored as strings. Unfortunately, even numbers and booleans are represented as strings ("5" and "false" respectively), which is not ideal ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

What is the best way to locate the closest element using JavaScript?

Is there a way to locate the closest object to the mouse pointer on a webpage? I have a hypothesis that involves utilizing the array function, however, I am uncertain if that is the correct approach. Furthermore, I lack knowledge of which specific proper ...

Error in Sequelize database: Column name does not exist in the database

The issue at hand involves a findAll product selector with a column labeled "PermissionId" that does not actually exist. I am puzzled as to why Sequelize is generating this non-existent column. The errors encountered are as follows: Unhandled rejectio ...

Tips for setting up Reaction Roles in discord.js?

Having some trouble implementing this functionality, especially with my reaction role. Wondering if I am using the correct functions/methods. Any help would be greatly appreciated. New to discord bot development and might have a simple question, but any a ...

Retrieve orders from a designated date using Picqer

Is there a method to retrieve past orders using the picqer API that were placed a few days ago? After examining the filters on their website, it appears that direct access to past orders is not possible through the API alone. Is there a workaround for thi ...

Saving an edited polygon path in Vue using Google Maps

In my Vue component named BaseMap, there is a nested component called Location. The Location component features an editable Polygon marker. // BaseMap <GmapMap> <Location :location="location" /> </GmapMap> // Location <gmap-marker ...