How to get a listing of key value pairs in an object?

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


You can loop through it:

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

Demo


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])
    }
}

Tags:

Javascript