1

I'm a javascript newbie.

I have a line of code:

data.content_teaser.image_square_attachment_url

square can change: I have a variable called contentType that can be 'square', or 'vertical' or 'horizontal'.

In ruby I can use send with the string interpolation, how can I obtain the same in js?

Something like "data.content_teaser.image_" + contentType + "_attachment_url"

Roberto Pezzali
  • 2,484
  • 2
  • 27
  • 56

2 Answers2

1

Javascript has 2 ways to access object properties/methods - dot-notation and square-bracket-notation. The latter uses a string what you could build up in the normal way you would for any string. So these 2 are equivalent:

data.content_teaser.image_square_attachment_url;
data.content_teaser["image_square_attachment_url"];

So, to answer your question:

var contentType = "square";
var result = data.content_teaser["image_" + contentType + "_attachment_url"];
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

You can use Javascript's string interpolation since ES2015 look here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals :

`string text ${expression} string text`

So, you can use something like this :

let s = `image_${contentType}_attachment_url`

And after that :

data.content_teaser[s]
geo
  • 2,283
  • 5
  • 28
  • 46