Barris
Barris

Reputation: 1019

Dynamically changing a method name in JavaScript

I have the following code:

headerCaptions.push(localization.SCREEN_EPISODE_INITIATION_HEADER_REQUEST1);
headerCaptions.push(localization.SCREEN_EPISODE_INITIATION_HEADER_REQUEST2);
headerCaptions.push(localization.SCREEN_EPISODE_INITIATION_HEADER_REQUEST3);

headerCaptions is an array. The localization object contains string values.

I want to generate this dynamically, i.e. map through x number of times, the number of the object parameter increasing by one with each iteration. For example to make 4 would make the final method call SCREEN_EPISODE_INITIATION_HEADER_REQUEST4 and so on.

I am happy to use vanilla js or the new ES6 syntax.

Upvotes: 0

Views: 49

Answers (5)

Cameron Martin
Cameron Martin

Reputation: 6012

The syntax a.b is equivalent to a['b'], so you can just do

for(var i = 1; i <= n; i++) {
  headerCaptions.push(localization['SCREEN_EPISODE_INITIATION_HEADER_REQUEST' + i]);
}

However, it might be better to just store these values in an array.

Upvotes: 0

void
void

Reputation: 36703

for(var i=0; i<5; i++){

    if(!localization.hasOwnProperty("SCREEN_EPISODE_INITIATION_HEADER_REQUEST"+i))
       break;

    headerCaptions.push(localization["SCREEN_EPISODE_INITIATION_HEADER_REQUEST"+i);

}

Upvotes: 0

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

You can use bracket notation in objects, to use variables like this:

headerCaptions.push(localization['SCREEN_EPISODE_INITIATION_HEADER_REQUEST'+i]);

Then you can use a loop:

for(var i = 0; i < 3; i++) {
    headerCaptions.push(localization['SCREEN_EPISODE_INITIATION_HEADER_REQUEST'+i]);
}

Upvotes: 2

James Long
James Long

Reputation: 4736

In JavaScript, you can access object properties using either the dot syntax (which you have used in your example) or the substring syntax, which looks like this:

headerCaptions.push(localization["SCREEN_EPISODE_INITIATION_HEADER_REQUEST1"]);

Since the square brackets just contain a string, it's possible to dynamically generate them.

headerCaptions.push(localization["SCREEN_EPISODE_INITIATION_HEADER_REQUEST" + i]);

Now all you need to do is loop through your numbers.

var i = 1;
var il = 4;
while (i < il) {

    headerCaptions.push(localization["SCREEN_EPISODE_INITIATION_HEADER_REQUEST" + i]);
    i += 1;

}

Upvotes: 1

Jonathan Windridge
Jonathan Windridge

Reputation: 407

Using ES6 syntax, you could call something like this:

const n = 4;
for (let i = 0; i < n; i++) {
  headerCaptions.push(localization[`SCREEN_EPISODE_INITIATION_HEADER_REQUEST${i}`])
}

Since JavaScript object attributes can be accessed either by calling object.property or object['property'], we can programatically access the attributes of location that are of interest by manipulating a string.

The `` syntax uses string interpolation, allowing you to insert computed values / variables into a string by surrounding it by ${}

Upvotes: 1

Related Questions