Home  >  Article  >  Web Front-end  >  How to check if an object is empty in Javascript

How to check if an object is empty in Javascript

青灯夜游
青灯夜游Original
2021-10-20 18:10:3519000browse

Method: 1. Convert the object into a json string and determine whether the string is "{}"; 2. Use the "$.isEmptyObject(object)" statement; 3. Use "Object.getOwnPropertyNames( Object)" statement; 4. Use "Object.keys(Object)".

How to check if an object is empty in Javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript checks whether the object is empty

1. Convert the json object into a json string, and then determine whether the string is "{ }"

var data = {};
var b = (JSON.stringify(data) == "{}");
alert(b);//true

2. jquery's isEmptyObject method

This method encapsulates the 2 methods (for in) by jquery. You need to rely on jquery

var data = {};
var b = $.isEmptyObject(data);
alert(b);//true
when using it.

3. Object.getOwnPropertyNames() method

This method uses the getOwnPropertyNames method of the Object object to obtain the property names in the object, store them in an array, and return the array object. We can judge the array by length to determine whether this object is empty

Note: This method is not compatible with ie8, and other browsers have not tested it

var data = {};
var arr = Object.getOwnPropertyNames(data);
alert(arr.length == 0);//true

4. Use the Object.keys() method of ES6

Similar to method 3, it is a new method of ES6. The return value is also an array composed of property names in the object

var data = {};
var arr = Object.keys(data);
alert(arr.length == 0);//true

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to check if an object is empty in Javascript. 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