-1

How to insert a variable into an address for reading a JSON file. It is supposed to be something like this. But this doesn't work. The first part works but that is a sample of how it is supposed to work. The working part is called workingMarketCap:

<!DOCTYPE html>
<html>
    <body>
    </body>

    <!--============================ SCRIPT ============================ -->
    <script>
        //Variables
        var myRequest = new XMLHttpRequest(); 
        var watchList = ["AAPL", "FB", "GOOGL", "MSFT"];
        var urlList = watchList.join(',');

        //IEX API requests open and send
        myRequest.open ('GET', `https://api.iextrading.com/1.0/stock/market/batch?symbols=${urlList}&types=quote`) //use API function "GET" to recieve data
        myRequest.send()

        //On the load of the data
        myRequest.onload = function(){
            var IEXData = JSON.parse(myRequest.responseText); //var IEXData converts JSON response to readable data for this code
            readData(IEXData, watchList); //output it into this HTML file         
        }

        /*
        =======================
            FUNCTIONS
        =======================
        */
        function readData(data, list) {
            for(var i = 0; i < 3; i++) {
                var workingMarketCap = data.AAPL.quote.marketCap;

                console.log(workingMarketCap);

                /* Does not work VVV */
                var marketCap = data.`${list[i]}`.quote.marketCap;

                console.log(marketCap);
            }
        }
    </script>
</html>
letsintegreat
  • 3,328
  • 4
  • 18
  • 39
  • What do you mean it's not working? Could you tell what you want to achieve and what is not working? – varun agarwal Mar 27 '19 at 03:29
  • this works ++ var workingMarketCap = data.AAPL.quote.marketCap; console.log(workingMarketCap); ++ this doesnt ++ var marketCap = data.`${list[i]}`.quote.marketCap; console.log(marketCap); ++ – Aleem Ahmed Mar 27 '19 at 05:11

1 Answers1

0

You can change your function to:

function readData(data, list) {
  for (var i = 0; i < list.length; i++) {
    var workingMarketCap = data.AAPL.quote.marketCap;
    console.log(workingMarketCap);

    var marketCap = data[list[i]].quote.marketCap;
    console.log(marketCap);
  }
}
varun agarwal
  • 1,491
  • 6
  • 9