0

I'm using Vue.js and I am wondering how I can call a javascript property in a dynamic way. Let's say I pass an argument to a function like this:

filter: function(items) {
    this.countriesToFilter.splice(index, 1);
},

How can I replace the countries in my this.countriesToFilter call in a dynamic way so I end up with essentially:

this.itemsToFilter.splice(index, 1);

3 Answers 3

1

Maybe this way?

filter: function(items) {
    var whatToFilter = items + 'ToFilter';
    this[whatToFilter].splice(index, 1);
},
Sign up to request clarification or add additional context in comments.

Comments

1

The answer is yes.

var name = "itemsToFilter";
var myArray = eval("this." + name);

// use myArray

You can also add a safety check so you don't call splice on undefined

if (typeof myArray != 'undefined') {
    myArray.splice(index, 1)
}

Comments

1

The only way I can imagine this working is if you pass a string to the function, and interpolate that string into the object-notation, using square-brackets:

filter: function(keyName) {
    this[keyName + 'ToFilter']splice(index, 1);
}

If your existing variable, items (from the question), contains a value of relevance within the function then you'd also need to pass that as an argument also:

filter: function(keyName, items) {
    this[keyName + 'ToFilter']splice(index, 1);
}

Comments

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.