0

I have a JSON file with many different columns as you can see below (I'm using BootstrapVue).

I want to get an array of one column and I want to filter it on duplicates.

My JSON file:

[
    { "Number": 111, "Input1": "Good morning", "Input2": "Test1" },
    { "Number": 222, "Input1": "Hello", "Input2": "Test2" },
    { "Number": 333, "Input1": "Good morning", "Input2": "Test2" },
    { "Number": 444, "Input1": "Ciao", "Input2": "Test2" },
    { "Number": 555, "Input1": "Hey", "Input2": "Test2" },
    { "Number": 666, "Input1": "Hey", "Input2": "Test2" }
]

I try to filter column 2 (Input1) and check duplicates - so the final array should look like this:

data():{
  return {
    Input1 = [{text: 'Good morning'}, {text: 'Hello'}, {text: 'Ciao'}, {text: 'Hey'}]
  }
}

I need it like this because it's for b-form-select fields.

1 Answer 1

1

Make it a computed property that loops through all values, takes only the Input1 value, then filter duplicates and finally map all to have the correct format.

Something like:

data: function(){
  return {
    selected: null,
    the_json: [
      { "Number": 111, "Input1": "Good morning", "Input2": "Test1" },
      { "Number": 222, "Input1": "Hello", "Input2": "Test2" },
      { "Number": 333, "Input1": "Good morning", "Input2": "Test2" },
      { "Number": 444, "Input1": "Ciao", "Input2": "Test2" },
      { "Number": 555, "Input1": "Hey", "Input2": "Test2" },
      { "Number": 666, "Input1": "Hey", "Input2": "Test2" }
    ]
  };
},
computed: {
  filtered_from_json: function() {
    let arr = this.the_json.map((v) => v.Input1); // Take only the `Input1` value
    return arr
      .filter((v, idx) => arr.indexOf(v) == idx) // Discard values that are present already (= lower index)
      .map((v) => { return {text: v, value: v}; }); // Transform value into object with property `text` of value
  }
},

And use like so: <b-form-select v-model="selected" :options="filtered_from_json"></b-form-select>

Sign up to request clarification or add additional context in comments.

4 Comments

thank you! but how can I reference it to my select form?
I'm not familiar with b-form-select, but in regular Vue it's something like <option v-for="item, idx in filtered_from_json" :key="idx" :value="item.text">{{ item.text }}</option>.
Oh, according to this documentation it should be :options="filtered_from_json". BUT: the return objects should also have a value property! So return {text: v}; becomes return {text: v, value: v};
I edited my answer to include the specific use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.