0

I'm having a problem iterating over my json in TypeScript. I'm having trouble with one specific json field, the tribe. For some reason I can't iterate over that one. In the debugger, I'm expecting the Orc to show up but instead I get a 0. Why is this? How do I iterate correctly over my tribe data?

// Maps a profession or tribe group name to a bucket of characters
let professionMap = new Map<string, Character[]>()
let tribeMap = new Map<string, Character[]>()

let herolistJson = require('./data/HeroList.json')

for (let hero of herolistJson){

  // Certain characters can have more than one tribe
  // !!!!! The trouble begins here, tribe is 0???
  for (let tribe in hero.tribe){
    let tribeBucket = tribeMap.get(tribe) as Character[]

    // If the hero does not already exist in this tribe bucket, add it
    if(tribeBucket.find(x => x.name == hero.name) === undefined )
    {
      tribeBucket.push(new Character(hero.name, hero.tribe, hero.profession, hero.cost))
    }
  }
}    

My json file looks like this

[
  { 
    "name": "Axe", 
    "tribe": ["Orc"], 
    "profession": "Warrior",
    "cost": 1
  },
  {
    "name": "Enchantress",
    "tribe": ["Beast"],
    "profession": "Druid",
    "cost": 1
  }
] 

2 Answers 2

1

in iterates over the keys of an object, not the values. The keys of an array are its indices. If you use of instead, you'll use the newer iterator protocol and an Array's iterator provides values instead of keys.

for (let tribe of /* in */ hero.tribe) {

Note, that this won't work in IE 11, but will work in most other browsers as well many JS environments that are ES2015 compatible. kangax/compat has a partial list.

Sign up to request clarification or add additional context in comments.

Comments

1

Change the "in" to "of" in second loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.