Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 269
Leila Hamon Avatar asked Jul 01 '12 02:07

Leila Hamon


1 Answers

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])     } } 
like image 97
sachleen Avatar answered Sep 17 '22 18:09

sachleen