0

I have a function that loops on an array, gets the value of the field Days on all objects, and assigns them to the property this.daysOptions

this is the function:

getMultiPicklistValues() {
        var valuesArray = [];
        for(let i=0;i<this.assets.length;i++) {
            if(!valuesArray.includes(this.assets[i].Days)) {
                valuesArray.push(this.assets[i].Days);
            }
        }
        var newArray = [];
        for(var i=0;i<valuesArray.length;i++) {
            newArray.push({'key':i+1,'value':valuesArray[i]});
        }

        this.daysOptions = newArray;
    }

I want to make this function generic, and assign newArray to some property, that will be changed dynamically, instead of assigning it to this.daysOptions

I changed the function to receive the field name, but how do i get the property name?

getMultiPicklistValues(fieldName) {
        var valuesArray = [];
        for(let i=0;i<this.assets.length;i++) {
            if(!valuesArray.includes(this.assets[i].get[fieldName])) {
                valuesArray.push(this.assets[i].get[fieldName]);
            }
        }
        var newArray = [];
        for(var i=0;i<valuesArray.length;i++) {
            newArray.push({'key':i+1,'value':valuesArray[i]});
        }

        //this.daysOptions = newArray;
    }
3
  • Did you try this[fieldName] = newArray? – Phil W Dec 10 '19 at 12:36
  • fieldName will be "Days", but i want to set the value to this.daysOptions – Dana Griff Dec 10 '19 at 12:36
  • Oh, so add a second parameter, e.g. "targetFieldName", and try this[targetFieldName] = newArray? – Phil W Dec 10 '19 at 12:38
2

Remember that an instance of a JavaScript class is just a JavaScript object and you can assign to a property of a JavaScript object either using:

theObject.propertyName = X;

or

theObject["propertyName"] = X;

You should, therefore, be able to use something like:

this[targetProperty] = newArray;

to set the component's property named by the targetProperty variable.

1
  • Thank you very much! – Dana Griff Dec 10 '19 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.