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"} 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]) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With