Home > Web Front-end > JS Tutorial > body text

How to check if a JavaScript object is empty

不言
Release: 2018-11-06 17:44:09
Original
2337 people have browsed it

This article will share with you how to check whether a JavaScript object is empty. Friends in need can refer to it. Let’s take a look at the specific content.

With JavaScript, it can be difficult to check if an object is empty. With Arrays you can easily check using myArray.length but on the other hand objects don't work this way and the best way to check if an object is empty or not is to use a utility function like below.

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
    }
Copy after login

If you have an empty object, you can use the above function to check if it is empty.

var myObj = {}; // Empty Object
if(isEmpty(myObj)) {
    // Object is empty (Would return true in this example)
    } else {
    // Object is NOT empty
    }
Copy after login

Alternatively, you can write the isEmpty function on the Object prototype.

Object.prototype.isEmpty = function() {
    for(var key in this) {
        if(this.hasOwnProperty(key))
            return false;
    }
    return true;
    }
Copy after login

Then you can easily check if the object is empty.

var myObj = {
    myKey: "Some Value"
    }
    if(myObj.isEmpty()) {
    // Object is empty
    } else {
    // Object is NOT empty (would return false in this example)
    }
Copy after login

Extending the object prototype is not the best thing to do, as it can cause some browser issues and other issues with some frameworks (it's also not always reliable in some environments). The examples I've given have almost nothing to do with frameworks.

This is a useful utility function, especially if you deal with many objects every day.

The above is the detailed content of How to check if a JavaScript object is empty. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template