0

I'm trying to find the best way to abstract away these three functions into one.

function displaySummary(data) {
  getMyElement('app__summary').innerHTML = data.summary;
  return data;
}

function displayTemperature(data) {
  getMyElement('app__temperature').innerHTML = data.temperature;
  return data;
}

function displayLocation(data) {
  getMyElement('app__location').innerHTML = data.location;
  return data;
}

As you can see, the three of them share the exact structure. The parameter is just a simple object with some properties.

What I would like to do is to be able to call one function with two arguments like so:

displayElement(data, 'location');

And have something like this run (note, this next one is pseudocode):

function displayElement(data, STRING) {
  getMyElement('app__STRING').innerHTML = data.STRING;
  return data;
}

How would you go about doing this? ES2015 syntax is welcome too.


META: I'm aware that this question might be flagged as a potential duplicate of the questions below. Neither of these answer how to interpolate (if at all possible) a string to work as a property accessor, which is mainly how I 'think' this problem should be solved. I'm open to suggestions and edits to make this question a better one.

EDIT: @Bergi flagged as duplicate a question that didn't come in my search and that does solve this question. Should I delete this one?

adeluccar
  • 152
  • 1
  • 2
  • 12

2 Answers2

0

You can use square bracket notation for reading the property and string concatenation for making the selector

function displayElement(data, prop) {
  getMyElement('app__' + prop).innerHTML = data[prop];
  return data;
}

if the string does not exactly match the property name, you could pass a third parameter which is a function to look up the right property:

 function displayElement(data, propName, lookup) {
  getMyElement('app__' + propName).innerHTML = lookup(data);
  return data;
}

Calling it as

// Note: Different casing of Location vs location
displayElement(data,"Location", d => d.location);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

See this documentation: https://www.w3schools.com/js/js_properties.asp

So in this case your function would be:

function displayElement(data, STRING) {
  getMyElement('app__'+STRING).innerHTML = data[STRING];
  return data;
}
Our_Benefactors
  • 3,220
  • 3
  • 21
  • 27