How do I log the name of the variable instead of the data associated with it?

Tags: ,



I am building a program on node.js that scans the prices of some currencies, and I am getting the prices, however I would like the program to also log the name of the currencies, not just the price. As you can see in the following code, the ‘currency’ variable in the console.log was my try to make the name show before logging the price.

    const currencies = [euro, yen];
    for (let currency of currencies) {    
        const pair = await fetchPairData(currency, dollar);
        const route = new Route([pair], dollar);
        console.log(currency + route.midPrice.toSignificant(6));
        }

But it seems like the currency variable wants to return the values associated with it, not the names of the currency… How do I switch that? Thanks for the help guys, step by step I will get good at this!

Answer

As soon as you do this:

const currencies = [euro, yen];

there is no link from currencies[0] back to euro or from currencies[1] back to yen. [euro, yen] takes the value of the euro and yen variables and puts those values in the array.

Trying for minimal changes to what you have, you could use an object rather than an array:

for (let [currencyName, currencyValue] of Object.entries({euro, yen})) {    
    const pair = await fetchPairData(currencyValue, dollar);
    const route = new Route([pair], dollar);
    console.log(currencyName, currencyValue + route.midPrice.toSignificant(6));
}

How that works:

  • {euro, yen} is an object literal using shorthand property notation; the longhand would be {euro: euro, yen: yen}. So you end up with an object with properties named "euro" and "yen" with the values from the euro and yen variables.
  • Object.entries creates an array of [name, value] pairs from an object’s own enumerable properties. The array ends up being :
    [ ["euro", euroValue], ["yen", yenValue] ]
    
    (You could, of course, just do that directly rather than via Object.entries({euro, yen}).)
  • for-of loops through the entries in that array.
  • I’m using destructuring assignment in the for-of to grab the name and value into separate constants.

But, ideally you’d change your starting point so you had pairs of names (of the currency) and values (the currency value) to start with, rather than creating them based on variable names.



Source: stackoverflow