user6552641
user6552641

Reputation:

Javascript getting data undefined on console when it shouldn't

I have this data:

{
   "id":"01",
   "new":0,
   "closed":0,
   "locked":0,
   "subhere":[
      {
         "id":"123",
         "subname":"somename"
      }

...etc...

In the console log I'm getting this to show (See comments):

console.log('Level 1 ID: ' + obj.id); //This works!
console.log('Level 1 Closed ' + obj.closed); //This works!
console.log('Level 1 Locked ' + obj.locked); //This works!
console.log('Level 2 Subhere ID ' + obj.subhere.id); //This returns Undefined!

The last console.log is giving me Undefined but I don't see what the problem is...why?

Any ideas on why I'm getting Undefined on the last one?

Upvotes: 0

Views: 154

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115202

Since obj.subhere is an array so obj.subhere.id will be undefined. You need to get array element first which is the object.

console.log('Level 2 Subhere ID ' + obj.subhere[0].id)
//---------------------------------------------^^^----

var obj = {
  "id": "01",
  "new": 0,
  "closed": 0,
  "locked": 0,
  "subhere": [{
    "id": "123",
    "subname": "somename"
  }]
};

console.log('Level 2 Subhere ID ' + obj.subhere[0].id)

Upvotes: 4

Ashisha Nautiyal
Ashisha Nautiyal

Reputation: 1397

You should use this

 console.log('Level 2 Subhere ID ' + obj.subhere[0].id); 

Upvotes: -1

Oskar Szura
Oskar Szura

Reputation: 2549

subhere is an array - and you're referring to it as an object.

Hence it should be rather:

console.log(obj.subhere[0].id); 

Upvotes: 5

Related Questions