Left Over
Left Over

Reputation: 251

How to determine an object in a given object in Javascript?

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?

Upvotes: 1

Views: 71

Answers (4)

dodov
dodov

Reputation: 5844

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"

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

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

Upvotes: 4

Nina Scholz
Nina Scholz

Reputation: 386560

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

Upvotes: 2

Nitesh
Nitesh

Reputation: 1550

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

Upvotes: 2

Related Questions