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');
}