-3

Let's say I have the following object:

var obj {
    name: "Jack", 
    id: 4, 
    year: "2004"
}

I want to iterate through the properties and print out the property type:

for (var i in obj) {
    console.log(i + ' (' + (typeof i) + ') ' + obj[i];
}

The problem is that every type shows as a string:

name: (string) Jack

id: (string) 4

year: (string) 2004

How can I get output the types of "Jack" and "2004" as string and 4 as integer/numeric or something?

Bas Peeters
  • 3,269
  • 4
  • 33
  • 49

1 Answers1

2

You are outputting the type of your key, not the value. It should be:

for (var prop in obj) {
    console.log(prop + ' (' + (typeof obj[prop]) + ') ' + obj[prop])
}                                     ^^^^^^^^^

That would output:

name (string) Jack
id (number) 4
year (string) 2004
putvande
  • 15,068
  • 3
  • 34
  • 50