0

I'm new to coding and just paying around, but i have what I think is really simple problem, but just don't have the necessary vocabulary to express it properly. Here is my code, its for currency conversion.

app.get('/currency', (request, response) => {
  const from_currency = request.query.from;
  const to_currency = request.query.to;
  const amount = request.query.amount;
  const exchange = `${from_currency}_${to_currency}`

  //https://free.currencyconverterapi.com/api/v5/convert?q=USD_PHP&compact=y
  const currencyUrl = `https://free.currencyconverterapi.com/api/v5/convert?q=${from_currency}_${to_currency}&compact=y`;

  const requestOptions = {
    uri: currencyUrl,
    json: true
  };

  requestPromise(requestOptions)
    .then((data) => {
      //const responseData = getCurrentCurrencyJSON(data);
      response.json(data); //responseData
    })
    .catch((error) => {
      console.log(error.message);
      response.json({
        messages: [{
          text: 'Sorry there was an error!'
        }]
      });
    });
});

This returns, from the API, {"USD_GBP":{"val":0.73897}}, which is fine and I can return the value if i write response.json(data.USD_GBP.val); however I want to be able to vary the currencies im converting to and from, so how do I make the USD_GBP in the response.json dynamic?

thanks if anyone can help.

McFlea83
  • 21
  • 6
  • You do have the key you're looking for; it's the one you pass to the API. Other than that, you can use `data[Object.keys[data][0]]` (the key word here is *bracket notation*) –  Jan 11 '18 at 20:26
  • 1
    Possible duplicate of [Dynamically Access Object Property Using Variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Patrick Evans Jan 11 '18 at 20:26
  • Thanks guys appreciate the info – McFlea83 Jan 13 '18 at 12:23

1 Answers1

0

If the api is always going to return an object with than single attribute, you can do something like this:

res = {"USD_GBP":{"val":0.73897}};
res[Object.keys(res)[0]].val

Not the nicest, but it works.

monstercode
  • 944
  • 6
  • 25