1

I have a JSON object:

 var json = {"Mike":1, "Jake":1, "Henry":1};

I am trying to loop through this list to access the names. Currently I am using:

for (var name in json) {
    if (json.hasOwnProperty(name)) {
        console.log(name);
    }
}

But it's not printing the name. Is that the correct way to do it?

jsFiddle: http://jsfiddle.net/bKwYq/

chhantyal
  • 11,874
  • 7
  • 51
  • 77

3 Answers3

0

It can be done by getting the key using Object.keys and then using foreach loop to print to console or display as alert message.

var persons = {"Mike":1, "Jake":1, "Henry":1};
var keysInPerson= Object.keys (persons);
keysInPerson.forEach ((name) => console.log (name));

//Alert
keysInPerson.forEach ((name) => alert (name));
0

As other people mentioned, this is not JSON, it's just an object.

The hasOwnProperty thing may not really be necessary here also.

var persons = {"Mike":1, "Jake":1, "Henry":1};
for (var name in persons) {
    alert(name);
}

This will work in every browser: http://jsfiddle.net/HsNMY/

Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
  • It will not work as intended if you add `Object.prototype.foo = 42` before your loop. This is why `hasOwnProperty` is recommended. – Phrogz Dec 07 '11 at 21:00
  • it's super recommended to not add anything to Object.prototype.foo, so all major libraries don't. – Jamund Ferguson Dec 07 '11 at 21:23
  • While I know that some major libraries forbid it (because they don't want to add `hasOwnProperty` in all their enumerations due to the speed hit), I'd like you to provide a citation for "super recommended". – Phrogz Dec 07 '11 at 21:26
  • http://stackoverflow.com/questions/6877005/extending-object-prototype-javascript http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/ http://erik.eae.net/archives/2005/06/06/22.13.54/ Extending natives I think is cool though, just not Object.prototype. This is great talk about it: http://blip.tv/jsconf/jsconf2011-andrew-dupont-everything-is-permitted-extending-built-ins-5211542 – Jamund Ferguson Dec 07 '11 at 21:33
  • Thanks. FWIW I personally find only the second URL convincing; the first is just a random opinion, and the third appears to be written by someone who clearly didn't understand how to write JavaScript code. Still, you have provided a citation as asked. :) – Phrogz Dec 07 '11 at 21:36
  • :) that video i posted about extending natives goes pretty deep into it though. – Jamund Ferguson Dec 07 '11 at 21:38
-2

The correct way to PRINT the name is to use document.write instead of console.log, as in this fiddle :

http://jsfiddle.net/jRAna/

Dominic Goulet
  • 7,983
  • 7
  • 28
  • 56
  • console.log is actually a nicer way to debug rather than printing to the page – TS- Dec 07 '11 at 21:21
  • wow so much hatred simply by responding to the actual question. Never said it was better to print it, just answered what was asked. – Dominic Goulet Dec 07 '11 at 23:59