0

I have an object... Ho can I retrieve its name

var data = {
  "FORD": {
    "PK RANGER": ["2012", "2013"],
    "PJ RANGER": ["2010", "2011"]
  },
  "HONDA": {
    "CRV": ["2007", "2008", "2009"]
  }
}

console.log(data.FORD);

data.FORD displays data inside it...

[object Object] {
  PJ RANGER: ["2010", "2011"],
  PK RANGER: ["2012", "2013"]
}

Is there a way where i can display its name like: FORD?

Omer
  • 1,727
  • 5
  • 28
  • 47

1 Answers1

1

Use a for loop for this. Like:

var data = {
  "FORD": {
    "PK RANGER": ["2012", "2013"],
    "PJ RANGER": ["2010", "2011"]
  },
  "HONDA": {
    "CRV": ["2007", "2008", "2009"]
  }
}
for (var i in data) {
  if (data.hasOwnProperty(i)) {
    console.log(i);
  }
}
gaganshera
  • 2,629
  • 1
  • 14
  • 21
  • is it necessary to add `var` keyword in for? can I write it like `for(i in data)`? – Omer May 07 '17 at 07:14
  • You can but its advised to always use a `var`, to limit the `i` variable's scope. Check [this](http://stackoverflow.com/questions/5717126/var-or-no-var-in-javascripts-for-in-loop) out to get a better understanding. – gaganshera May 07 '17 at 08:03
  • Also can I add loop inside the loop to get the sub objects name? Like PK RANGER and PJ RANGER? – Omer May 07 '17 at 10:46
  • Yes since the sub objects are objects themselves, you can loop through them like above. – gaganshera May 07 '17 at 10:48
  • I tried but it shows me "0" "1" "2" .... http://jsbin.com/weqevug/edit?js,console – Omer May 07 '17 at 10:55
  • How did you try it? – gaganshera May 07 '17 at 10:55
  • Is my object defined properly ... I think something not right in it. – Omer May 07 '17 at 10:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/143597/discussion-between-omer-and-gaganshera). – Omer May 07 '17 at 10:56