Bim Bam
Bim Bam

Reputation: 439

Can't get data from parsed JSON (Nodejs)

I have JSON file:

{
    "Abilities": {
        "ability_base": {
            ...
        },
        "some_data": {
            ...
        },
    }
}

Parsed it with:

var obj = JSON.parse(fs.readFileSync('./npc_abilities.json'));

And try to get some data from it. I made:

for (var key in obj) {
    console.log(obj.Abilities.ability_base);
}

It shows me data from "ability base" {...}, it is correct behavior. But when I tried to get all keys, of my Abilities object:

for (var key in obj) {
    console.log(obj.Abilities[key]);
}

It shows me "undefined" in console. Why? How can I get all objects inside Abilities?

Upvotes: 0

Views: 38

Answers (1)

maazadeeb
maazadeeb

Reputation: 6112

You're iterating over the wrong object. You can try this

var obj = {
  "Abilities": {
    "ability_base": {
      a: 1
    },
    "some_data": {
      b: 2
    },
  }
};

// Iterating over obj
for (var key in obj) {
  console.log("Key: ", key);
  console.log(obj.Abilities[key]);
}

console.log("*****************************");

// Need to iterate over obj.Abilities
for (var key in obj.Abilities) {
  console.log("Key: ", key);
  console.log(obj.Abilities[key]);
}

Notice the console.log of the key in both the cases. I believe you require the second for loop and not the first one.

Upvotes: 2

Related Questions