Home > Enterprise >  Get array of JSON column and check on duplicates / VueJS
Get array of JSON column and check on duplicates / VueJS

Time:09-27

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.

CodePudding user response:

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>

  • Related