-1

I am a newcomer to JavaScript and learning now. I am using for/in to print a properties and the value of each property of a object. But I am able to print only the properties but not the property values.

Code snippet:

var obj = {x:1,y:2,z:3}
var disp_obj = function(obj){ for(p in obj) console.log(p, obj.p) }
disp_obj(obj)

And the output is: x undefined y undefined z undefined

As I can see from the output, only the property names are printed but not its values. Please correct me what is wrong with this?

Anonymous
  • 11,748
  • 6
  • 35
  • 57
Pradeep
  • 1,057
  • 2
  • 9
  • 17
  • 1
    Use `obj[p]` instead of `obj.p`, because in the latter case it's treated as a bare word and not a subscript. – Ja͢ck Jun 20 '14 at 12:45
  • `obj.p` means get the property `p` of `obj`. What you need is `obj[p]` which means get the property with the name stored in variable `p` of `obj`. – Matt Burland Jun 20 '14 at 12:46
  • Ok, Got it.So if the object 'obj' has a property named 'p', it would have printed. – Pradeep Jun 20 '14 at 12:53

3 Answers3

3

When you use .p after the object reference, it won't use the variable p to evaluate that, it will always get the proptery named "p".

Use bracket syntax to access a property using a string:

console.log(p, obj[p]);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

If you want to access an object's property using the value of a variable, you'll have to use the bracket notation, not the dot notation:

var dispObj = function(o)
{
    for (var p in o)
        console.log(p, o[p]);
};

Be weary, though: your dispObj creates a global variable p, because you omitted the var keyword. Also try to strick to coding standards, JS functions are camelCased.
In general, your simple for...in loop will perform just fine, but in some cases you might end up logging properties that trickled down from the prototype chain. It is, then, recommended to make sure you only log the properties of that object:

for (var p in o)
    if (o.hasOwnProperty(p))
        console.log(p, o[p]);
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
0

Change

var disp_obj = function(obj){ for(p in obj) console.log(p, obj.p) }

to

var disp_obj = function(obj){ for(var p in obj) console.log(p, obj[p]) }

More info on bracket access notation here.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thanks, also Can I ask why 'var p' is required, Cant the only 'p' in 'for' will suffice? – Pradeep Jun 20 '14 at 12:55
  • Not declaring a variables makes it global (or erases one in the outer scope), which is a major cause of bug. Imagine you're calling from your loop another function also using p and declaring it as global ? – Denys Séguret Jun 20 '14 at 13:04