24

Possible Duplicate:
best way to get the key of a key/value javascript object

foo = {bar: "baz"}

How do you get a listing of all the properties and values within foo?

Community
  • 1
  • 1
Leila Hamon
  • 2,505
  • 7
  • 24
  • 32

3 Answers3

47

A for in loop can give you the key and value. Remember to use const, let or var for variable declaration in strict mode.

for(const p in foo) {
    console.log (p, foo[p])
}

From the console:

foo = {bar: "baz"}

Object
bar: "baz"
__proto__: Object

for(p in foo) { console.log (p, foo[p]) }
> bar baz

If the object you're looping over has has inherited properties from its prototype, you can prevent the inherited properties from being looped over using the Object.hasOwnProperty() function like this:

for(const p in foo) {
    if (foo.hasOwnProperty(p)) {
        console.log (p, foo[p])
    }
}
Yongkin
  • 69
  • 1
  • 7
sachleen
  • 30,730
  • 8
  • 78
  • 73
1

You can loop through it:

for(var i in foo) {
  console.log( i + ": " + foo[i] + "<br />");
}

Demo

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

This can be different for the different platforms that you are currently working on. If you are running from terminal then you use print, if you dont have the console object then you can use document.write() and so on.

Here is something that you can use/read to understand:

var foo = {bar: "baz", boolean: true, num: 2}

for (i in foo) {
//checks to see where to print.
if (typeof console === 'object') 
    console.log(i + ": " + foo[i]);
else if (typeof document === 'object') 
    document.write(i + ": " + foo[i]);
else 
    print(i + ": " + foo[i]);
}

Alternatively, if you just say console.log(foo) in Chrome/Firefox, the browsers do the looping-highlighting for you and give you a pretty-print of your object, so you dont really need to do the looping shown above.

You can also use console.debug(foo) instead of console.log(foo), the difference is subtle. You can read more about this at http://getfirebug.com/wiki/index.php/Console_API

dtx
  • 626
  • 1
  • 7
  • 12