1

Let's say I have an Object-

var obj = { 
    name : 'John',
    contact : { 
           address : 'xyz',
           phone : 555
    }
}

Now when I loop through this object

for (let key in obj) {
     console.log(typeof key);
}

In Both cases I get type of 'string'. So is there any way to get contact value as an object?

4 Answers 4

4

Your key actually contains "name" and "contact" strings.

If you want to detect type of a value contained in contact property, you need to access it this way:

typeof obj[key]

Demo:

var obj = { 
  name : 'John',
  contact : { 
   address : 'xyz',
   phone : 555
  }
}

for (let key in obj) {
  console.log(key + " (key is " + typeof key + ", value is " + typeof obj[key] + "):");
  console.log(obj[key]);
}

Sign up to request clarification or add additional context in comments.

Comments

2

You are trying to find type of key whereas you should find type of value like, typeof obj[key]

Comments

2

You need to address the value of the property with a property accessor

console.log(typeof obj[key]);
//                 ^^^^^^^^

Otherwise, you get always 'string', because keys of objects are strings.

var obj = { name : 'John', contact : { address : 'xyz', phone : 555 } };

for (let key in obj) {
    console.log(typeof obj[key]);
}

Comments

1

You could do this without any looping, if you know the key of the property you want:

var obj = {
  name: 'John',
  contact: {
    address: 'xyz',
    phone: 555
  }
};

console.log(obj.contact);
console.log(obj["contact"]);
console.log(typeof obj.contact);
console.log(typeof obj["contact"]);

When using a loop, "contact" turns into a variable. This means you access the property like this:

for (var key in obj) {
    console.log(obj[key]); // key === "contact"
}

instead of this:

obj["contact"]

You should also note the difference between obj.key and obj[key]:

var obj = {
  key: "this_is_a_key",
  foo: "this_is_a_foo"
};

var key = "foo";
console.log(obj.key); // returns the "key" property
console.log(obj[key]); // returns the "foo" property because the key variable holds "foo"

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.