Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  147] [ 3]  / answers: 1 / hits: 69983  / 12 Years ago, sun, july 1, 2012, 12:00:00

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?


More From » javascript

 Answers
88

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

[#84551] Friday, June 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quinlanhenryf

Total Points: 743
Total Questions: 93
Total Answers: 118

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
;