Search code examples
javascriptecmascript-5es5-compatiblity

How to convert the code used with dictionary to ES5?


The code below works well in new browsers with dictionaries like

var CRAFT_DB = {
  6: {
    id: "6",
    type: "blockC",
    name: "local name",
    recipes: [{
      type: "new",
      count: "2",
      input: [
        [{
          index: "4",
          count: "1"
        }],
        [{
          index: "21",
          count: "1"
        }]
      ]
    }]
  }
}

var input = CRAFT_DB[6].recipes[0].input;
var ingredients = {};
for (var key in input)
    ingredients[input[key][0].index] = void 0 === ingredients[input[key][0].index] ? parseInt(input[key][0].count) : ingredients[input[key][0].index] + parseInt(input[key][0].count);

But I should support ES5. But I get the error TypeError: Cannot read property "index" from undefined with ES5-enabled browser.

I tried to convert the code to ES5 with https://babeljs.io/repl, but it didn't help.

How could I fix it?


Solution

  • The following verification helped me -

    for (var key in input) {
        if (typeof input[key][0] !== 'undefined') {
          ...
        }
     }