How to convert the code used with dictionary to ES5?

187 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

The following verification helped me -

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

In earlier versions of JS a lot of the built-in properties on arrays are enumerable.

When you loop over them with in you get those as well as the integer indexes.

input['length'] is going to be undefined, as is input['push'].

Use a regular for (var i = 0; i < index.length; i++) loop.