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

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?

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"}

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

You can loop through it:

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


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]);
    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.

Read More:   How to get base url with jquery or javascript?

You can also use console.debug(foo) instead of console.log(foo), the difference is subtle. You can read more about this at

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts