Как проверить объект на пустоту js

от admin

Методы объектов js: Как проверить объект Javascript на пустоту?

Проверить является ли объект пустым – одна из постоянно встречающихся задач в повседневной жизни Javascript разработчика.

Например, работая над очередной фичей в React приложении, требовалось делать активной кнопку “Подтвердить” только в том случае, когда объект const order = <> содержал свойства, то есть не был пустым.

В случае если бы переменная order содержала массив, то все было бы просто:

Рассмотрим 4 метода объектов js, которые помогут проверить объект на пустоту.

1. Object.keys()

Первый способ — использовать метод Object.keys() для получения нового массива из ключей (свойств) объекта. Если свойства отсутствуют, то новый массив будет пустой.

Тоже самое можно записать так:

Далее прописываем переменную для свойства disabled нашей кнопки (делаем ее неактивной):

2. JSON.stringify()

Второй способ проверить объект на пустоту — использовать метод JSON.stringify() , чтобы перевести наш объект в строчный формат и сравнить результат со строкой '<>' .

Добавляем наше условие:

3. Цикл for..in

Данный способ интересен тем, что его поддерживают более старые версии браузеров. Ознакомиться с текущим состоянием браузерной совместимости цикла for..in можно здесь ).

Давайте создадим функцию, которая принимает на вход объект и использует цикл for..in , чтобы пробежаться по ключам объекта. Далее используем метод object.hasOwnProperty() для проверки наличия ключа.

Функция возвращает true , в случае если ключи отсутствуют. Мы получим значение false , если в объекте присутствует хотя бы один ключ.

4. isEmpty (метод в библиотеке Lodash)

В библиотеке Lodash есть специальный метод, который принимает на вход как массивы так и объекты:

How to Check if an Object Is Empty in JavaScript

Sajal Soni Last updated Apr 29, 2022

In this quick article, I’ll show you how you can check if an object is empty in JavaScript.

In your day-to-day JavaScript development, you might need to check if an object is empty or not. And if you’ve had to do this, you probably know that there’s no single direct solution. However, there are different techniques that you can use to create a custom solution for your own use case. Apart from that, if you’re using a JavaScript utility library in your project, there’s a chance that it already provides a built-in method to check if an object is empty.

The Modern Way (ES5+)

In this section, we’ll discuss the different methods that you could use in modern browsers that support the ES5 edition.

1. The Object.keys() Method

The Object.keys() method returns an array of enumerable property names of a given object. And thus, we can use it to check if an object has any properties by counting the length of this array.

Let’s have a look at the following example.

As you can see in the above example, the bar object has the foo property attached to it, and thus the bar.keys(obj).length expression would return a value greater than zero. So the isEmptyObject function would return false in this case.

Go ahead and test the isEmptyObject function with different values.

Note that the Object.keys() method can return some surprising results for special types. For example, isEmptyObject will return true for a Date or RegExp object.

Also, be careful because calling this method with a null or undefined value. They would result in an exception. Later on, we’ll create a bullet-proof solution that won’t fail on a null input.

2. The Object.getOwnPropertyNames() Method

The Object.getOwnPropertyNames() method returns an array of all the properties of a given object. Although it may look identical to the Object.keys() method, there’s a difference. The Object.getOwnPropertyNames() method also considers the non-enumerable properties, while the Object.keys() only considers enumerable properties. Most of the time, these will be equivalent, but there is a risk that Object.keys() will miss certain properties that have been declared not to be enumerable.

Let’s go through the following example.

As you can see, testing emptiness with Object.getOwnPropertyNames() works similarly to using Object.keys() .

The edge cases are a bit different, though—the Object.getOwnPropertyNames() method will still return true for a Date , but will return false for a RegExp .

Once again, this method will fail on a null or undefined input.

3. JSON.stringify

The JSON.stringify method is used to convert a JavaScript object to a JSON string. So we can use it to convert an object to a string, and we can compare the result with <> to check if the given object is empty.

Let’s go through the following example.

Once again, the edge cases are a bit different. JSON.stringify will return a numeric string like «1651283138454» for a Date , but will return an empty object for a RegExp . So using the JSON.stringify method gives exactly the opposite results for these classes to the Object.getOwnPropertyNames method!

Another twist is that the JSON.stringify method won’t throw an exception on a null input. Instead, it will return false , which might not be what you would expect.

4. Object.entries()

The Object.entries() method returns an array of arrays, with each element being an array of key-value pairs of an object’s property.

Let’s go through the following example to understand how it works exactly.

As you can see, the Object.entries() method converts an object into an array, and we can count the length of that array to check if the object in question is empty.

This is very similar to the Object.keys() method and will give the same results on our edge case examples of Date and RegExp objects. It will also throw an exception for a null or undefined input.

A Bullet-Proof Solution

A problem with the simple solutions above is that they give inconsistent results for edge cases: special objects like RegExp or Date , null or undefined values, or primitives like integers. Here’s a simple but more bullet-proof solution.

This method does exactly what it says: it returns true exactly if the input value is both an object and is empty. It will work with null and undefined values—returning false because these are not objects. For special objects like Date and RegExp , it will return true because they don’t have any special keys defined. It will also return true for an empty array and false for a non-empty array.

The Pre-ES5 Way

In this section, we’ll discuss a solution which would work even with older browsers. This was used frequently until the JavaScript ES5 era, when there were no built-in methods available to check if an object is empty.

Let’s go through the following example.

In the above example, we’ve built a custom function which you can call to check if an object is empty. It takes a single argument, and you need to pass an object which you want to test. In the isEmptyObject function, we try to iterate over the object properties. If the object has any properties, we’ll return FALSE , otherwise we’ll return TRUE .

You can go ahead and test the isEmptyObject function with different values. As shown in the above example, we’ve called it with different values and logged the output with the console.log function.

Читать:
Документ содержит связи с другими файлами как убрать

So that’s how you can check if an object is empty in browsers that don’t support the ES5 edition. In the next section, we’ll discuss it in the context of modern browsers.

The jQuery Way

If you’re already using the jQuery library in your project, it’s really easy to check if an object is empty, since the jQuery library already provides the isEmptyObject method, which allows you to check if an object is empty.

Let’s quickly go through the following example.

As you can see, it’s fairly straightforward to use the isEmptyObject method with jQuery.

Similarly, the Lodash and Underscore.js libraries have _.isEmpty() .

Conclusion

In this article, we discussed a number of different ways to check if an object is empty or not in JavaScript. Check out some of our other tutorials about JavaScript programming!

This post has been updated with contributions from Neema Muganga.

How to check if an object is empty in JavaScript

For JavaScript objects, there is no built-in .length or .isEmpty method available to check if they are empty.

Please enable JavaScript

Here are 4 different methods that you can use to make sure that a given object does not have its own properties:

Object.entries() Method

The Object.entries() method takes an object as an argument and returns an array of its enumerable property [key, value] pairs.

We can then use the .length property of the array to check if it contains any item:

Note: Object.entries() only works in modern browsers and is not supported by IE. If you need backward compatibility, consider adding a polyfill or use Oject.keys() method instead.

Object.keys() Method

The Object.keys() method is the best way to check if an object is empty because it is supported by almost all browsers, including IE9+.

It returns an array of a given object’s own property names. So we can simply check the length of the array afterward:

Object.getOwnPropertyNames() Method

The Object.getOwnPropertyNames() method takes an object as parameter and returns an array of its own property names:

3rd-Party Libraries

If you are already using 3rd-party libraries like jQuery or Lodash in your web application, you can also use them to check if an object is empty:

Prototype Function

You can write a helper function isEmpty() and add it to the object’s prototype:

Now you can call the isEmpty() method on any JavaScript object to check if it has its own properties:

Be careful while extending the Object prototype, as it can cause issues when used together with other JavaScript frameworks. Instead, use the Object.keys() method in JavaScript applications to check if an object is empty.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

# How to Check if Object is Empty in JavaScript

Here’s a Code Recipe to check if an object is empty or not. For newer browsers, you can use plain vanilla JS and use the new "Object.keys" �� But for older browser support, you can install the Lodash library and use their "isEmpty" method ��

# What is Vanilla JavaScript

Vanilla JavaScript is not a new framework or library. It’s just regular, plain JavaScript without the use of a library like Lodash or jQuery.

# A. Empty Object Check in Newer Browsers

We can use the built-in Object.keys method to check for an empty object.

# Why do we need an additional constructor check?

You may be wondering why do we need the constructor check. Well, it’s to cover for the wrapper instances. In JavaScript, we have 9 built-in constructors.

So we can create an empty object with new Object() . Side note: you should NEVER create an object using the constructor. It’s considered bad practice, see Airbnb Style Guide

So just using the Object.keys , it does return true when the object is empty ✅. But what happens when we create a new object instance using these other constructors.

Ah ya ya, we have a false positive ��

# Solving false positive with constructor check

Let’s correct this by adding a constructor check.

Beautiful! We have covered our edge case ��

# Testing empty check on other values

Alright, let’s test our method on some values and see what we get ��

Looks good so far, it returns false for non-objects.

��But watch out! These values will throw an error.

# Improve empty check for null and undefined

If you don’t want it to throw a TypeError , you can add an extra check:

Perfect, no error is thrown ��

# B. Empty Object Check in Older Browsers

What if you need to support older browsers? Heck, who am I kidding! We all know when I say older browsers, I’m referring to Internet Explorer �� Well, we have 2 options. We can stick with vanilla or utilize a library.

# Checking empty object with JavaScript

The plain vanilla way is not as concise. But it does do the job ��

It returns true for objects.

Excellent, it doesn’t get trick by our constructor objects ��

And we’re covered for null and undefined . It will return false and not throw a TypeError .

# Checking empty object with external libraries

There are tons of external libraries you can use to check for empty objects. And most of them have great support for older browsers ��

Lodash

Underscore

jQuery

# Vanilla vs Libraries

The answer is it depends! I’m a huge fan of going vanilla whenever possible as I don’t like the overhead of an external library. Plus for smaller apps, I’m too lazy to set up the external library ��. But if your app already has an external library installed, then go ahead and use it. You will know your app better than anyone else. So choose what works best for your situation ��

# Conscious Decision Making

I love this mindset so much! Often, we have to make some compromises. And there’s nothing wrong with that. Especially, when you work within a team, sometimes disagreement arises. But in the end, we have to make a decision. This doesn’t mean we blind ourselves from other options. Quite the opposite, we do our best to seek other possible solutions and understand each implication. That’s how we can make an informed decision. Maybe compromise is not the right word, I think of it as "conscious decision making" ��

Yup, I too can coin terms, just like Gwyneth Paltrow’s conscious uncoupling

. Maybe I should start a tech version of Goop. but minus the jade roller and the other "interesting" products ��

# Community Input

: Lodash tends to throw security exceptions in analysis tools like sonarqube and whitesource, I tend to just create my own util function and use vanilla instead.

Похожие статьи