9
Author: Samantha Ming
Translator: Frontend Xiaozhi
Source: medium

If you have dreams and dry goods, search for [Great Move to the World] still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

We are hiring, annual salary: 250,000-600,000 + bonus, if you are interested, you can click me for details.

The following code snippet is used to check whether the object is empty. For newer browsers, you can use ES6 "Object.keys". 🍦For older browsers, you can install the Lodash library and use its "isEmpty" method.

const empty = {};

/* -------------------------
  较新的浏览器
----------------------------*/
Object.keys(empty).length === 0 && empty.constructor === Object
// true

/* -------------------------
  老版本的浏览器可以使用 Lodash
----------------------------*/
_.isEmpty(empty)
// true

What is native JavaScript

Native JavaScript refers to not using frameworks or libraries. It is just regular ordinary JavaScript and does not use libraries such as Lodash or jQuery

A. Check for empty objects in newer browsers

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

const empty = {};

Object.keys(empty).length === 0 && empty.constructor === object;

Why do we need an additional constructor check?

You may be wondering why we need to check constructor It is to cover the wrapper instance. In JavaScript, we have 9 built-in constructors.

new Object();

new String();
new Number();
new Boolean();
new Array();
new RegExp();
new Function();
new Date();

Here, we can use new Object() create an empty object.

Note: Never use constructors to create objects. This is considered bad practice, please refer to Airbnb Style Guide and ESLint .
const obj = new Object();

Object.keys(obj).length === 0; // true

Therefore, using only Object.keys , when the object is empty, it will indeed return true . But what happens when we use other constructors to create new object instances.

function badEmptyCheck(value) {
  return Object.keys(value).length === 0;
}

badEmptyCheck(new String());    // true 😱
badEmptyCheck(new Number());    // true 😱
badEmptyCheck(new Boolean());   // true 😱
badEmptyCheck(new Array());     // true 😱
badEmptyCheck(new RegExp());    // true 😱
badEmptyCheck(new Function());  // true 😱
badEmptyCheck(new Date());      // true 😱

Resolve false positives by checking the constructor

Correct this error by adding a constructor check.

function goodEmptyCheck(value) {
  Object.keys(value).length === 0
    && value.constructor === Object; // 👈 constructor check
}

goodEmptyCheck(new String());   // false ✅
goodEmptyCheck(new Number());   // false ✅
goodEmptyCheck(new Boolean());  // false ✅
goodEmptyCheck(new Array());    // false ✅
goodEmptyCheck(new RegExp());   // false ✅
goodEmptyCheck(new Function()); // false ✅
goodEmptyCheck(new Date());     // false ✅

Nice, good job 👍

Null check for other values

Next, we test our method with some values to see what we will get 🧪

function isEmptyObject(value) {
  return Object.keys(value).length === 0 && value.constructor === Object;
}

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

isEmptyObject(100)  // false
isEmptyObject(true) // false
isEmptyObject([])   // false

🚨But be careful! The following values will cause an error.

// TypeError: Cannot covert undefined or null to object
isEmptyObject(undefined);
isEmptyObject(null);

Improve the null check null and undefined

If you don’t want it to throw TypeError , you can add additional checks

function isEmptyObject(value) {
  return value && Object.keys(value).length === 0 && value.constructor === Object;
}

B. Empty object check in older browsers

What if you need to support older browsers? Everyone knows that when we talk about old browsers, we mean IE . We have two choices, using native or using libraries.

Use JavaScript to check for empty objects

Native JS is not so concise, but it is okay to judge to use empty objects.


function isObjectEmpty(value) {
  return (
    Object.prototype.toString.call(value) === '[object Object]' && JSON.stringify(value) === '{}'
  );
}

For objects, it returns true .

isObjectEmpty({});           // true ✅
isObjectEmpty(new Object()); // true ✅

Other types of constructors can also be judged normally😉

isObjectEmpty(new String());   // false ✅
isObjectEmpty(new Number());   // false ✅
isObjectEmpty(new Boolean());  // false ✅
isObjectEmpty(new Array());    // false ✅
isObjectEmpty(new RegExp());   // false ✅
isObjectEmpty(new Function()); // false ✅
isObjectEmpty(new Date());     // false ✅

Incoming null and undefined will not report TypeError .

isObjectEmpty(null);      // false
isObjectEmpty(undefined); // false

Use an external library to check for empty objects

There are a large number of external libraries that can be used to check for empty objects. And most of them have good support for old browsers👍

Lodash

_.isEmpty({});
// true

Underscore

_.isEmpty({});
// true

jQuery

jQuery.isEmptyObject({});
// true

Native VS library

The answer depends on the situation! I really like to simplify the program as much as possible, because I don't like the overhead of external libraries. In addition, for smaller applications, I am too lazy to set up external libraries. But if your application already has an external library installed, then continue to use it. You will know your application better than anyone. So choose the method that best suits your situation

Talents' [Three Lian] is the biggest motivation for Xiaozhi to keep sharing. If there are any mistakes or suggestions in this blog, we welcome talents to leave a message. Finally, thank you for watching.


possible bugs in 16196f0142a332 editing cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://www.samanthaming.com/tidbits/94-how-to-check-if-object-is-empty/#what-is-javascript

comminicate

The article is continuously updated every week, and you can search on [Great Move to the World] Read it for the first time, reply to [Benefit] are many front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhizhi has been included, welcome to Star.


王大冶
68.1k 声望105k 粉丝