-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?

2
  • What's the real code ? Where does i come from ? Commented May 30, 2015 at 13:19
  • @DenysSéguret What do you mean where's the real code? It's all there Commented May 30, 2015 at 13:21

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.