mistersalami
mistersalami

Reputation: 1

forEach into for loop

I have the following games object:

window.games ={
    "game1": {
        name: "game1", 
        url: "", 
    },
    "game2": {
        name: "game2", 
        url: "", 
    },
    "game3": {
        name: "game3", 
        url: "", 
    },
    "game4": {
        name: "game4", 
        url: "", 
    },
};

and the following selected games array

window.selectedGames = ["game2", "game3"];

I am using a forEach to take each game from the selected games array and using the data from the object to render an html element:

 selectedGames.forEach(game => {
        for (var [key, value] of Object.entries(games)) {
            if (key === game) {
                var jackpotContainer = document.querySelector(".sub-jackpot-container");
                gameContainer = document.createElement('div');
                jackpotContainer.appendChild(gameContainer);
                gameBox = document.createElement('div');
                link = document.createElement('a');
                link.href = value.url;
                gameContainer.appendChild(gameBox);
                gameContainer.appendChild(link);
                gameName = document.createElement('span');
                gameName.classList = 'game-name';
                gameName.innerHTML = value.name;
            }
        }
    });

I cannot figure out how can I change this forEach into a for loop so this can be supported on IE as well. I'll be very thankful for any help.

Upvotes: 0

Views: 106

Answers (3)

Namaskar
Namaskar

Reputation: 2109

Instead of trying to refactor all of your code to support IE, you can use a transpiler such as Babel to convert all of your code. For your example input, babel will output something like

"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

selectedGames.forEach(function (game) {
  for (var _i = 0, _Object$entries = Object.entries(games); _i < _Object$entries.length; _i++) {
    var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
        key = _Object$entries$_i[0],
        value = _Object$entries$_i[1];

    if (key === game) {
      var jackpotContainer = document.querySelector(".sub-jackpot-container");
      gameContainer = document.createElement('div');
      jackpotContainer.appendChild(gameContainer);
      gameBox = document.createElement('div');
      link = document.createElement('a');
      link.href = value.url;
      gameContainer.appendChild(gameBox);
      gameContainer.appendChild(link);
      gameName = document.createElement('span');
      gameName.classList = 'game-name';
      gameName.innerHTML = value.name;
    }
  }
});

See it here. Look up how to include it in your build process as you should not be actually putting code in the online editor. This is just for testing.

Upvotes: 1

Swetank Poddar
Swetank Poddar

Reputation: 1291

Looking at your loop I think its better to loop through the elements you want rather than looping through everything and checking if it matches or not.

Something like this:

window.games ={
    "game1": {
        name: "game1", 
        url: "", 
    },
    "game2": {
        name: "game2", 
        url: "", 
    },
    "game3": {
        name: "game3", 
        url: "", 
    },
    "game4": {
        name: "game4", 
        url: "", 
    },
};

window.selectedGames = ["game2", "game3"];

window.selectedGames.forEach(selected_game => {
  game = window.games[selected_game];
  
  if (game !== undefined) {
    // You can do whatever you want here
    console.log(game.name);
    console.log(game.url);
  }
  
 });

Upvotes: 0

Aioros
Aioros

Reputation: 4383

selectedGames.forEach(game => {
    // ...
});

would become:

for (var i=0; i < selectedGames.length; i++) {
    var game = selectedGames[i];
    // ....
}

Upvotes: 1

Related Questions