Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, How to determine if an object property exists and is not empty?

Tags:

Suppose I have the next javascript object:

var errors = {
    error_1: "Error 1 description",
    error_2: "Error 2 description",
    error_3: "",
    error_4: "Error 4 description"
};

How can I determine if the property error_1 exists in the errors object and is not empty as well?

like image 417
Amr Avatar asked Feb 17 '15 00:02

Amr


People also ask

How do you check if a property exists in an object in JavaScript?

JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .

How do you check if an object has no properties in JavaScript?

keys() method to check if there are any properties defined in an object. It returns an array of object's own keys (or property names). We can use that array to check if it's length is equal to 0 . If it is, then it means the object has no properties.

How do you check if a JSON object is empty or not in node JS?

if (isEmptyObject(query)) { // There are no queries. } else { // There is at least one query, // or at least the query object is not empty. } Show activity on this post. If using underscore or jQuery, you can use their isEmpty or isEmptyObject calls.


1 Answers

if (errors.hasOwnProperty('error_1') && errors['error_1'] )

The method hasOwnProperty can be used to determine whether an object has the specified property as a direct property of that object.

The errors[key] where key is a string value checks if the value exists and is not null

to Check if its not empty where it is a string then typeof errors['error_1'] === 'string' && errors['error_1'].length where you are checking for the length of a string

Result:

if (errors.hasOwnProperty('error_1') && typeof errors['error_1'] === 'string' && errors['error_1'].length)

Now, if you are using a library like underscore you can use a bunch of utility classes like _.isEmpty _.has(obj,key) and _.isString()

like image 50
AhmadAssaf Avatar answered Oct 15 '22 08:10

AhmadAssaf