0

In a Vue project there are 3 methods that have the same basic structure:

data() {
    return {
      itemIDs: [],
      locnIDsOut: [],
      locnIDsIn: []
    }
  },
  methods: {
    populateItemIDs() {
      this.itemIDs = [...new Set(this.data.map(o => o.itemID))]
        .map(o => ({
          key: o
        }))
        .sort(firstBy(function(a) {
          return a.key
        }));
    },
    populateLocnIDsOut() {
      this.locnIDsOut = [...new Set(this.data.map(o => o.locnIDOut))]
        .map(o => ({
          key: o
        }))
        .sort(firstBy(function(a) {
          return a.key
        }));
    },
    populateLocnIDsIn() {
      this.locnIDsIn = [...new Set(this.data.map(o => o.locnIDIn))]
        .map(o => ({
          key: o
        }))
        .sort(firstBy(function(a) {
          return a.key
        }));
    }
  }

The code is quite redundant - only the property name changes in the Set line of each method. Is there a way to pass a property name into a generic method? I tried this by the syntax is not right -

populateByProperty(propertyName) {
  this. {
      propertyName
    } = [...new Set(this.data.map(o => o.{
      propertyName
    }))]
    .map(o => ({
      key: o
    }))
    .sort(firstBy(function(a) {
      return a.key
    }));
}

The goal is to be able to call the generic method from the created() hook, like this:

created() {
  this.itemIDs = this.populateByProperty('itemID');
  this.locnIDsOut = this.populateByProperty('locnIDOut');
  this.locnIDsIn = this.populateByproperty('locnIDIn');
}
knot22
  • 2,648
  • 5
  • 31
  • 51
  • 1
    `o[propertyName]` where `propertyName` is the variable containing the string that you want to get. `x.y` is equavilent to `x['y']` – Taplar Oct 30 '20 at 20:38
  • 1
    Also relevant: [Dynamically access object property using variable](https://stackoverflow.com/q/4244896) | [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/q/4968406) – VLAZ Oct 30 '20 at 20:39

0 Answers0