Home > Back-end >  get two values of json into <b-form-select> text-field
get two values of json into <b-form-select> text-field

Time:11-23

I'm working with BootstrapVue.

I have a json with following structure:

[
    {"ID": "123", "Name": "Harry", "Age": "22"},
    {"ID": "456", "Name": "Harry", "Age": "18"},
    {"ID": "789", "Name": "Peter", "Age": "20"},
    {"ID": "159", "Name": "Peter", "Age": "19"},
]

So at least, just to make clear, every data - based from Name and Age together - is unique, also without the ID (!). It's just a example to make it easier to understand.

What I try to do is now to show the Name in a <b-form-select> with the Age in brackets behind. Like this for e.g.: Peter (20).

In the moment I have following code:

<b-form-select :options="sortedPersons" text-field="Name" value-field="ID"></b-form-select>

I need to pass value to my parent.vue but want to show text in this one. So I've decided to do this like that.

The only thing I need now is to get following. This example is to show it simply what I want:

:text-field="'Name' ' ' '(' 'Age' ')'", but this doesn't work.

How can I make it run?

Additional Info - I'm running my json in computed before to sort it.

sortedPersons() {
  var array = this.json.map((input) => input);
  return array.sort((a, b) => {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
  });
},

Thanks in advance!

CodePudding user response:

You'll either need to map your data so the text you want is formatted in a single property, or instead drop using the options prop and instead manually create the <option> tags using a v-for.

new Vue({
  el: "#app",
  data() {
    return {
      selected: '',
      options: [
          {"ID": "123", "Name": "Harry", "Age": "22"},
          {"ID": "456", "Name": "Harry", "Age": "18"},
          {"ID": "789", "Name": "Peter", "Age": "20"},
          {"ID": "159", "Name": "Peter", "Age": "19"},
      ]
    };
  }
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/[email protected]/dist/css/bootstrap.min.css" />
<script src="//unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="//unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>


<div id="app" class="p-4">
  <b-select v-model="selected">
    <option v-for="option in options" :key="option.ID" :value="option.ID">
      {{ option.Name }} ({{ option.Age }})
    </option>
  </b-select>

  Selected: {{ selected }}
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related