Home >Web Front-end >JS Tutorial >How Can I Effectively Determine if a JavaScript Object is Empty?

How Can I Effectively Determine if a JavaScript Object is Empty?

DDD
DDDOriginal
2024-12-24 14:00:19502browse

How Can I Effectively Determine if a JavaScript Object is Empty?

Determining the Emptiness of JavaScript Objects

To ascertain whether a JavaScript object is empty, various methods and considerations are available. One approach involves utilizing a for...in loop in conjunction with Object.hasOwn (ECMA 2022 ). This loop iterates through an object's own properties and returns false if any exist:

function isEmpty(obj) {
  for (const prop in obj) {
    if (Object.hasOwn(obj, prop)) {
      return false;
    }
  }

  return true;
}

Another method distinguishes tussen empty objects and other objects lacking own properties. This can be achieved through type checks:

function isEmptyObject(value) {
  if (value == null) {
    return false;
  }

  if (typeof value !== 'object') {
    return false;
  }

  const proto = Object.getPrototypeOf(value);

  if (proto !== null && proto !== Object.prototype) {
    return false;
  }

  return isEmpty(value);
}

It's crucial to note that comparing against Object.prototype may overlook cross-realm objects. Additionally, Object.keys(obj).length is discouraged as it's inefficient, requiring the creation of an array.

For compatibility with older JavaScript engines, Object.hasOwn can be replaced with Object.prototype.hasOwnProperty.call:

function isEmpty(obj) {
  for (var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      return false;
    }
  }

  return true;
}

Various libraries offer functions specifically designed to check for empty objects:

  • jQuery: jQuery.isEmptyObject({}) // true
  • Lodash: _.isEmpty({}) // true
  • Underscore: _.isEmpty({}) // true
  • Hoek: Hoek.deepEqual({}, {}) // true
  • ExtJS: Ext.Object.isEmpty({}) // true
  • AngularJS (version 1): angular.equals({}, {}) // true
  • Ramda: R.isEmpty({}) // true

The above is the detailed content of How Can I Effectively Determine if a JavaScript Object is Empty?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn