After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
After an AJAX request, sometimes my application may return an empty object, like:
var a = {};
How can I check whether that's the case?
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // null and undefined check
&& Object.keys(obj).length === 0 && obj.constructor === Object
Note, though, that this creates an unnecessary array (the return value of keys
).
Pre-ECMA 5:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
jQuery.isEmptyObject({}); // true
_.isEmpty({}); // true
_.isEmpty({}); // true
Hoek.deepEqual({}, {}); // true
Ext.Object.isEmpty({}); // true
angular.equals({}, {}); // true
R.isEmpty({}); // true
If ECMAScript 5 support is available, you can use Object.keys()
:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
For ES3 and older, there's no easy way to do this. You'll have to loop over the properties explicitly:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
For those of you who have the same problem but use jQuery, you can use jQuery.isEmptyObject.
This is my preferred solution:
var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
You can use Underscore.js.
_.isEmpty({}); // true
Today 2020.01.17, I performed tests on macOS High Sierra 10.13.6 on Chrome v79.0, Safari v13.0.4, and Firefox v72.0; for the chosen solutions.
for-in
(A, J, L, M) are fastestJSON.stringify
(B, K) are slowObject
(N) is also slowThere are 15 solutions presented in the snippet below. If you want to run a performance test on your machine, click HERE. This link was updated 2021.07.08, but tests originally were performed here - and results in the table above came from there (but now it looks like that service no longer works).
var log = (s, f) => console.log(`${s} --> {}:${f({})} {k:2}:${f({ k: 2 })}`);
function A(obj) {
for (var i in obj) return false;
return true;
}
function B(obj) {
return JSON.stringify(obj) === "{}";
}
function C(obj) {
return Object.keys(obj).length === 0;
}
function D(obj) {
return Object.entries(obj).length === 0;
}
function E(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
function F(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
function G(obj) {
return typeof obj === "undefined" || !Boolean(Object.keys(obj)[0]);
}
function H(obj) {
return Object.entries(obj).length === 0 && obj.constructor === Object;
}
function I(obj) {
return Object.values(obj).every((val) => typeof val === "undefined");
}
function J(obj) {
for (const key in obj) {
if (hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
function K(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
function L(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) return false;
}
return true;
}
function M(obj) {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
return false;
}
}
return true;
}
function N(obj) {
return (
Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
Object.getPrototypeOf(obj) === Object.prototype
);
}
function O(obj) {
return !(Object.getOwnPropertyNames !== undefined
? Object.getOwnPropertyNames(obj).length !== 0
: (function () {
for (var key in obj) break;
return key !== null && key !== undefined;
})());
}
log("A", A);
log("B", B);
log("C", C);
log("D", D);
log("E", E);
log("F", F);
log("G", G);
log("H", H);
log("I", I);
log("J", J);
log("K", K);
log("L", L);
log("M", M);
log("N", N);
log("O", O);
If my answer was of any help, you can buy me a coffee.
if(Object.getOwnPropertyNames(obj).length === 0){
//is empty
}
see http://bencollier.net/2011/04/javascript-is-an-object-empty/
How about using JSON.stringify? It is almost available in all modern browsers.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:
function isEmptyObject(obj) {
var name;
for (name in obj) {
if (obj.hasOwnProperty(name)) {
return false;
}
}
return true;
}
I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.
And what I did was, used the following condition, and it worked for me.
var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
//Code here..
}
For not equal to, use this : JSON.stringify(obj) !== '{}'
Check out this JSFiddle
There is a simple way if you are on a newer browser.
Object.keys(obj).length == 0
Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.
Tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:
Bottom line performance wise, use:
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
or
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
See detailed testing results and test code at Is object empty?
You could check for the count of the Object keys:
if (Object.keys(a).length > 0) {
// not empty
}
Just a workaround. Can your server generate some special property in case of no data?
For example:
var a = {empty:true};
Then you can easily check it in your AJAX callback code.
Another way to check it:
if (a.toSource() === "({})") // then 'a' is empty
EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.
As per the ES2017 specification on Object.entries(), the check is simple using any modern browser--
Object.entries({}).length === 0
I've created a complete function to determine if object is empty.
It uses Object.keys
from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).
/**
* Returns true if specified object has no properties,
* false otherwise.
*
* @param {object} object
* @returns {boolean}
*/
function isObjectEmpty(object)
{
if ('object' !== typeof object) {
throw new Error('Object must be specified.');
}
if (null === object) {
return true;
}
if ('undefined' !== Object.keys) {
// Using ECMAScript 5 feature.
return (0 === Object.keys(object).length);
} else {
// Using legacy compatibility mode.
for (var key in object) {
if (object.hasOwnProperty(key)) {
return false;
}
}
return true;
}
}
Here's the Gist for this code.
And here's the JSFiddle with demonstration and a simple test.
I hope it will help someone. Cheers!
My take:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
var a = {
a: 1,
b: 2
}
var b = {}
console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true
Just, I don't think all browsers implement Object.keys()
currently.
I am using this.
function isObjectEmpty(object) {
var isEmpty = true;
for (keys in object) {
isEmpty = false;
break; // exiting since we found that the object is not empty
}
return isEmpty;
}
Eg:
var myObject = {}; // Object is empty
var isEmpty = isObjectEmpty(myObject); // will return true;
// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"};
// check if the object is empty
isEmpty = isObjectEmpty(myObject); // will return false;
Update
OR
you can use the jQuery implementation of isEmptyObject
function isEmptyObject(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
function isEmpty(obj) {
for(var i in obj) { return false; }
return true;
}
The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.
The script works on ES6.
const isEmpty = (obj) => {
if (obj === null ||
obj === undefined ||
Array.isArray(obj) ||
typeof obj !== 'object'
) {
return true;
}
return Object.getOwnPropertyNames(obj).length === 0;
};
console.clear();
console.log('-----');
console.log(isEmpty('')); // true
console.log(isEmpty(33)); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello')); // true
console.log(isEmpty([1, 2, 3])); // true
console.log(isEmpty({ test: 1 })); // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date())); // true
console.log(isEmpty(Infinity)); // true
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
I would go for checking if it has at least one key. That would suffice to tell me that it's not empty.
Boolean(Object.keys(obj || {})[0]) // obj || {} checks for undefined
jQuery have special function isEmptyObject()
for this case:
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
Read more on http://api.jquery.com/jQuery.isEmptyObject/
Under the hood all empty check methods in all libraries use object keys checking logic. Its an odd way to make it understandable, which you can put in a method, Described here.
for(key in obj){
//your work here.
break;
}
Which has evolved in ES5, now put simply you can check the object's keys length, using Object.Keys
method which takes your object as it's parameter:
if(Object.keys(obj).length > 0){
//do your work here
}
Or if you are using Lodash (you must be) then.
_.isEmpty(obj) //==true or false
you can use this simple code that did not use jQuery or other libraries
var a=({});
//check is an empty object
if(JSON.stringify(a)=='{}') {
alert('it is empty');
} else {
alert('it is not empty');
}
JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.
Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.
var a=({});
function isEmptyObject(obj) {
if(typeof obj!='object') {
//it is not object, so is not empty
return false;
} else {
var x,i=0;
for(x in obj) {
i++;
}
if(i>0) {
//this object has some properties or methods
return false;
} else {
//this object has not any property or method
return true;
}
}
}
alert(isEmptyObject(a)); //true is alerted
Best way that I found:
function isEmpty(obj)
{
if (!obj)
{
return true;
}
if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
{
return true;
}
return false;
}
Works for:
t1: {} -> true
t2: {0:1} -: false
t3: [] -> true
t4: [2] -> false
t5: null -> true
t6: undefined -> true
t7: "" -> true
t8: "a" -> false
t9: 0 -> true
t10: 1 -> false
If jQuery and the web browser is not available, there is also an isEmpty function in underscore.js.
_.isEmpty({}) // returns true
Additionally, it does not assume the input parameter to be an object. For a list or string or undefined, it will also turn the correct answer.
The correct answer is:
const isEmptyObject = obj =>
Object.getOwnPropertyNames(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
Object.getPrototypeOf(obj) === Object.prototype;
This checks that:
Object.prototype
.In other words, the object is indistinguishable from one created with {}
.
A simpler solution: var a = {};
Case a is empty: !Object.keys(a).length
returns true
.
2021 - solution
What you need is Object.entries(obj).length
. It's not good to touch in native prototype.
You can just create your own function and use it as you want. In my case I have a folder called utils
where I have a module definition like this:
utils/isEmpty.js
export default (obj) => !Object.entries(obj).length
someFileToUse.js
import isEmpty from '~/utils/isEmpty.js'
const obj1 = {};
const obj2 = {somekey: "someValue"};
console.log(isEmpty(obj1))
// -> true
console.log(isEmpty(obj2))
// -> false
In addition to Thevs answer:
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
it's jquery + jquery.json
Retrieved from : http:www.stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
How can I pair socks from a pile efficiently? (0) | 2023.05.16 |
---|---|
Squash my last X commits together using Git (0) | 2023.05.16 |
How do I UPDATE from a SELECT in SQL Server? (0) | 2023.05.16 |
How do I push a new local branch to a remote Git repository and track it too? (0) | 2023.05.16 |
How to enumerate an enum (0) | 2023.05.16 |