laitimes

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

author:Cloud source wants IT training
[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

"This is the cloud source to think about IT, to help you learn IT easily"

Hi~ How are you doing today?

The moment you want to live,

The spark of life has already been lit.

- 2024.01.26 -

When developing JavaScript applications, it is often necessary to check if the object is empty. This is because when working with and manipulating object data, we need to make sure that the object contains valid values or attributes.

In this article, we'll discuss how to check if an object is empty, including the different ways in JavaScript to check if an object is empty and how to check if an object is empty, undefined, or null.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

1. Under what circumstances do you need to check whether the object is empty?

Here are some common situations where we need to check if a JavaScript object is empty:

1. Prevent Null Reference Error:

When we try to access or use an empty object, it can cause a null reference error (such as TypeError: Cannot read property 'x' of null). By checking if the object is empty, we can avoid these errors and take action accordingly.

2. Data Validation and Form Submission:

Before a form can be submitted, it is often necessary to verify that the data entered by the user is valid. If the object is empty, indicating that the user did not provide the necessary data or did not fill in the form fields, we can display an error message or block the form submission.

3. Conditional logic and process control:

Depending on whether the object is empty or not, different operations can be performed or different branches can be taken based on different conditional logic. For example, if the object is empty, you can perform an alternate default action or return a default value.

4. Data Processing and Transformation:

Object data may need to be processed or transformed before it can be processed. If the object is empty, you can terminate or skip the data processing logic early to avoid unnecessary calculations or errors.

5. User interface interaction and display:

In the user interface, you may need to show or hide specific interface elements, change styles, or render different content depending on the presence or absence of objects.

By checking if a JavaScript object is empty, you can increase the robustness of your application, improve the user experience, and avoid potential errors and exceptions. Therefore, checking if an object is empty is an important part of writing high-quality code.

Here are some common ways to check if an object is empty:

2. Use Object.keys()

Use the Object.keys() method to check if an object is empty. Object.keys (obj) returns an array containing all enumerable properties of a given object.

With this feature, we can determine if an object is empty by checking the length of the returned array. If the array length is 0, it means that the object does not have any properties, that is, it is empty.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

Pros: Simple and easy to use, no need to rely on third-party libraries.

Disadvantages: Unable to handle properties that are not primitive types, such as functions, undefined, etc.

Here's a sample code:

javascriptCopy Codefunction isObjectEmpty(obj) {
  return Object.keys(obj).length === 0;
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log(isObjectEmpty(obj2)); // false           

In the example above, we define an isObjectEmpty() function that accepts an object as an argument. Internally, the function uses Object.keys(obj) to get all the enumerable properties of the object and check if the returned array length is 0. Based on the returned result, determine whether the object is empty.

3. Use Object.values()

Use the Object.values() method to check if an object is empty, and the Object.values(obj) method returns an array containing all enumerable property values for a given object. If the length of the returned array is 0, it means that the object does not have any property values, that is, it is empty.

Advantages: You can form an array of the attribute values of the object, and you can judge whether the object is empty by judging the length of the array.

Disadvantages: It is not possible to directly determine whether the object is empty or not, and only an array of attribute values is provided.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

Here's an example code that uses the Object.values() method to check if an object is empty:

function isObjectEmpty(obj) {
  return Object.values(obj).length === 0;
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log(isObjectEmpty(obj2)); // false           

In the example above, we define an isObjectEmpty() function that accepts an object as an argument. Internally, the function uses Object.values(obj) to get all the enumerable property values of the object and check if the returned array length is 0. Based on the returned result, determine whether the object is empty.

Note that the Object.values() method is a new method introduced in ES2017 (ES8) and therefore may not be supported in some older versions of the JavaScript engine. Before using it, make sure your environment supports the method or use an appropriate polyfill to do so.

Fourth, use for... in loop

Using for... The in loop method determines whether an object is empty by traversing its properties.

Pros: Non-primitive types of properties can be handled.

Disadvantages: The code is lengthy and you need to manually determine whether each property is an object property.

Here's a sample code:

javascriptCopy Codefunction isObjectEmpty(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false; // 只要有一个属性存在,就返回false表示不为空
    }
  }
  return true; // 如果遍历完所有属性后仍然没有返回false,表示对象为空
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log(isObjectEmpty(obj2)); // false           

In the example above, the isObjectEmpty() function accepts an object as an argument. Internally, the function uses for... in loops through the properties of the object, returning false if any properties are found, indicating that the object is not empty, and returning true if it still does not return false after the loop ends.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

While using for... The in loop serves the same purpose, but it's a bit more cumbersome to implement than using the Object.keys() or Object.values() methods. Therefore, in general, it is recommended to use the Object.keys() or Object.values() methods to check if an object is empty, as they provide a more concise and intuitive way.

5. Use Object.entries()

The Object.entries() method returns an array of key-value pairs that can be enumerated for a given object itself. If the returned array length is 0, it means that the object does not have any properties, that is, it is empty.

Advantages: You can form an array of key-value pairs of objects, and you can judge whether the object is empty by judging the length of the array.

Disadvantages: It is also impossible to directly determine whether an object is empty or not, and only provides an array of key-value pairs.

Here's an example code that uses the Object.entries() method to check if an object is empty:

function isObjectEmpty(obj) {
  return Object.entries(obj).length === 0;
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log(isObjectEmpty(obj2)); // false           

In the example above, the isObjectEmpty() function accepts an object as an argument. Inside the function, use Object.entries(obj) to get the key-value pair array of the object, and check if the returned array length is 0. If the array length is 0, it means that the object does not have any properties, that is, it is empty.

6. Use JSON.stringify()

The way to use the JSON.stringify() method to check if an object is empty is to convert the object to a JSON string and then check if the string is 2 in length. When the object is empty, the converted string is "{}" with a length of 2. If the object is not empty, the converted string length will be greater than 2.

Pros: Non-primitive type properties can be handled, and a converted string length of 2 means the object is empty.

Disadvantage: An exception is thrown when an object contains a circular reference.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

Here's an example code that uses the JSON.stringify() method to check if an object is empty:

function isObjectEmpty(obj) {
  return JSON.stringify(obj) === "{}";
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log(isObjectEmpty(obj2)); // false           

In the example above, the isObjectEmpty() function accepts an object as a parameter. Internally, the function uses JSON.stringify(obj) to convert the object to a JSON string, and then compares the converted string to "{}". If it is equal, it means that the object is empty.

It is important to note that this approach only works with pure objects and does not contain any non-primitive type properties (e.g. functions, undefined, etc.). If an object contains properties that are not of the original type, the converted JSON string may not be empty, even if the object is actually empty.

Here I would like to share with you the [Cloud Source Thought] learning platform, whether you are a beginner or an experienced developer, here is everything you need. Including course videos, knowledge base, micro-practice, cloud labs, one-on-one consultation, etc., now all the features are free, click here, start your learning journey now!

七、Object.getOwnPropertyNames()

In ES6, you can use the Object.getOwnPropertyNames() method to check if an object is empty, but be aware that this method returns an array containing all of its own properties in a given object (including non-enumerable properties, but not properties that use the symbol value as their name).

Advantages: It can return an array of all the property names of the object itself, including enumerable and non-enumerable attributes, and can judge whether the object is empty by judging the length of the array.

Disadvantages: It is also impossible to directly determine whether the object is empty, and only an array of property names is provided.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

Here's an example code that uses the Object.getOwnPropertyNames() method to check if an object is empty:

function isObjectEmpty(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log(isObjectEmpty(obj2)); // false           

In the example above, the isObjectEmpty() function accepts an object as an argument. Inside the function, use Object.getOwnPropertyNames(obj) to get all the property names of the object and check if the returned array length is 0. If the array length is 0, it means that the object does not have any properties, that is, it is empty.

Note that the array returned by the Object.getOwnPropertyNames() method contains only the object's own properties, not inherited properties. If you need to check inherited properties, use for... in loops or other methods.

Similarly, the Object.getOwnPropertyNames() method was introduced in ES5 and therefore may not be supported in some older versions of JavaScript engines.

八、Object.getOwnPropertySymbols()

In ES6, you can use the Object.getOwnPropertySymbols() method to check if an object is empty. The method returns an array containing all the symbolic properties of a given object itself.

Advantages: It can return an array of attributes of all Symbol types of the object itself, and you can judge whether the object is empty by judging the length of the array.

Disadvantages: It is only for properties of type Symbol, and it is not possible to tell whether other types of properties are empty.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

Here's an example code that uses the Object.getOwnPropertySymbols() method to check if an object is empty:

function isObjectEmpty(obj) {
  const symbols = Object.getOwnPropertySymbols(obj);
  const hasSymbols = symbols.length > 0;
  return !hasSymbols;
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const symbol = Symbol("key");
const obj2 = { [symbol]: "value" };
console.log(isObjectEmpty(obj2)); // false           

In the example above, the isObjectEmpty() function accepts an object as an argument. Internally, the function uses Object.getOwnPropertySymbols(obj) to get all the symbol properties of the object and store them in an array of symbols.

Then, tell if the object has a symbol property by checking if the length of the symbols array is greater than 0. If the length of the symbols array is 0, it means that the object does not have any symbol properties, that is, it is empty.

Note that the Object.getOwnPropertySymbols() method only returns the symbol properties of the object itself, and does not include other types of properties, such as string properties.

If you want to check both the string and symbol properties of an object, you can use a combination of the Object.getOwnPropertyNames() and Object.getOwnPropertySymbols() methods.

九、ES6使用Reflect.ownKeys()

In ES6, you can use the Reflect.ownKeys() method to check if an object is empty. Reflect.ownKeys() returns an array containing all of the properties of the specified object itself, including string and symbol keys.

Advantages: It can return an array of all the properties of the object itself (including string keys and symbol keys), including enumerable and non-enumerable properties, and you can judge whether the object is empty by judging the length of the array.

Disadvantages: Again, it is not possible to directly determine whether the object is empty or not, only an array of all keys is provided.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

Here's an example code that uses the Reflect.ownKeys() method to check if an object is empty:

function isObjectEmpty(obj) {
  return Reflect.ownKeys(obj).length === 0;
}

// 测试对象是否为空
const obj1 = {};
console.log(isObjectEmpty(obj1)); // true

const symbol = Symbol("key");
const obj2 = { [symbol]: "value" };
console.log(isObjectEmpty(obj2)); // false           

In the example above, the isObjectEmpty() function accepts an object as an argument. Internally, the function uses Reflect.ownKeys(obj) to get all of the object's own property names (including string keys and symbol keys), and checks whether the returned array length is 0. If the array length is 0, it means that the object does not have any properties, that is, it is empty.

The Reflect.ownKeys() method provides a unified way to get all the keys for an object, including string and symbol keys. Therefore, using the Reflect.ownKeys() method allows a more comprehensive check if an object is empty.

十、使用lodash库的isEmpty()函数

If you are using the lodash library, you can use the isEmpty() function provided by it to directly determine whether an object is empty or not.

Pros: It can handle a variety of cases, including non-primitively typed properties, arrays, strings, and more.

Disadvantages: Need to rely on third-party libraries.

Here's an example code for an object's null check using Lodash's isEmpty() function:

// 导入Lodash库
const _ = require('lodash');

// 检查对象是否为空
const obj1 = {};
console.log(_.isEmpty(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log(_.isEmpty(obj2)); // false           

In the example above, the _.isEmpty() function accepts an object as an argument and returns a boolean value indicating whether the object is empty or not. Returns true if the object is empty; false otherwise.

Using Lodash's isEmpty() function makes it easier to check for the absence of an object, while handling a variety of cases, including non-primitively typed properties, arrays, strings, and so on.

11. Use the $.isEmptyObject() function of the jQuery library

To use the $.isEmptyObject() function in the jQuery library to check if a JavaScript object is empty, first make sure that the jQuery library is installed and imported into your project.

Pros: It can handle a variety of cases, including non-primitively typed properties, arrays, strings, and more.

Disadvantages: Need to rely on third-party libraries.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

Here's an example code for an object's null check using jQuery's $.isEmptyObject() function:

// 导入jQuery库
const $ = require('jquery');

// 检查对象是否为空
const obj1 = {};
console.log($.isEmptyObject(obj1)); // true

const obj2 = { name: "John", age: 25 };
console.log($.isEmptyObject(obj2)); // false           

In the example above, the $.isEmptyObject() function accepts an object as an argument and returns a boolean value indicating whether the object is empty or not. Returns true if the object is empty; false otherwise.

Using jQuery's $.isEmptyObject() function makes it easier to do object null checking, while handling a variety of cases, including non-primitively typed properties, arrays, strings, and so on.

12. Check whether the object is empty, undefined, or null

To check if an object is empty, undefined, or null at the same time, you can use the following function to tell if it's null:

function isObjectEmptyOrNull(obj) {
  return obj === undefined || obj === null || Object.getOwnPropertyNames(obj).length === 0;
}           

In the above code, the isObjectEmptyOrNull function receives an object as an argument. It first checks whether the object is undefined or null, and if it is, it returns true to indicate that the object is empty or undefined.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

If the object is not undefined or null, use the Object.getOwnPropertyNames() method to get all the property names of the object, and then determine whether the length of the property name array is 0. If the array of attribute names is 0 in length, it means that the object does not have any attributes, that is, it is empty.

Here's an example usage:

const obj1 = {};
console.log(isObjectEmptyOrNull(obj1)); // true

const obj2 = null;
console.log(isObjectEmptyOrNull(obj2)); // true

const obj3 = { name: "John", age: 25 };
console.log(isObjectEmptyOrNull(obj3)); // false

const obj4 = undefined;
console.log(isObjectEmptyOrNull(obj4)); // true           

In general, these methods provide an indirect way to determine whether an object is empty, that is, by taking an array of objects' attributes, attribute values, or key-value pairs, and judging the length of the array.

However, they don't directly tell us whether an object is null or not, as they only provide information about attributes, property values, or key-value pairs. Therefore, when using these methods to determine whether an object is empty, it is necessary to consider it comprehensively in combination with other judgment conditions.

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!

See you next time!

END

Copywriting Editor|Cloud Senior

Copywriting with pictures|Cloud seniors

Content by: Cloud source wants to share

[Dry goods] article to master the N skills of JavaScript to check the null value of objects!
Dry

Read on