Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript. how can I tell if a field exists inside an object?

Tags:

javascript

And of course I want to do this code-wise. It's not that there isn't alternative to this problem I'm facing, just curious.

like image 218
Khoi Avatar asked Aug 13 '10 11:08

Khoi


People also ask

How do you know if a field exists?

1. To determine if a field exists in a particular substructure, use 'isfield' on that substructure instead of the top level. In the example, the value of a.b is itself a structure, and you can call 'isfield' on it. Note: If the first input argument is not a structure array, then 'isfield' returns 0 (false).

How do I check if an object contains a property?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.

How do you check if a key exists in an object?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.


2 Answers

This will ignore attributes passed down through the prototype chain.

if(obj.hasOwnProperty('field')) {     // Do something } 
like image 182
Gary Chambers Avatar answered Sep 17 '22 05:09

Gary Chambers


UPDATE: use the hasOwnProperty method as Gary Chambers suggests. The solution below will work, but it's considered best practice to use hasOwnProperty.

if ('field' in obj) { } 
like image 36
Peter Kruithof Avatar answered Sep 17 '22 05:09

Peter Kruithof