How do I test for an empty JavaScript object?
ECMA 5+:
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // null and undefined check
&& Object.keys(obj).length === 0
&& Object.getPrototypeOf(obj) === Object.prototype
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(Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
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
javascript - check if object is empty
You were testing sellers
which is not empty because it contains mergedSellerArray
. You need to test sellers.mergedSellerArray
let sellers = {
"mergedSellerArray": {}
};
if (Object.keys(sellers.mergedSellerArray).length === 0 && sellers.mergedSellerArray.constructor === Object) {
console.log("sellers is empty!");
} else {
console.log("sellers is not empty !");
}
Check if Object is Empty in ES6
You can do this way
const checkIfVerifiedExists = (user) => {
if (user && user.verified && Object.keys(user.verified).length) {
return true;
}
return false;
};
console.log(checkIfVerifiedExists(null));
console.log(checkIfVerifiedExists({something: "a"}));
console.log(checkIfVerifiedExists({verified: null}));
console.log(checkIfVerifiedExists({verified: ""}));
console.log(checkIfVerifiedExists({verified: "a"}));
console.log(checkIfVerifiedExists({verified: "a", something: "b"}));
Is object empty?
I'm assuming that by empty you mean "has no properties of its own".
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
Examples:
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames
instead of the hasOwnProperty
loop:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
This will ensure that even if the object only has non-enumerable properties isEmpty
will still give you the correct results.
How do I test for an empty JavaScript object?
ECMA 5+:
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // null and undefined check
&& Object.keys(obj).length === 0
&& Object.getPrototypeOf(obj) === Object.prototype
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(Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
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
How to check if object is empty in javascript for all levels in object
Here is the way to do what using recursion
const x = {
a:"",
b:[],
c:{
x:[]
},
d:{
x:{
y:{
z:''
}
}
}
};
function checkEmpty(obj){
for(let key in obj){
//if the value is 'object'
if(obj[key] instanceof Object === true){
if(checkEmpty(obj[key]) === false) return false;
}
//if value is string/number
else{
//if array or string have length is not 0.
if(obj[key].length !== 0) return false;
}
}
return true;
}
console.log(checkEmpty(x))
x.d.x.y.z = 0;
console.log(checkEmpty(x));
How to determine if a variable is an empty object, empty array or empty string?
Simply use Object.keys()
if (Object.keys(something).length) console.log("Not empty");
This works for all of strings, arrays, and of course, objects.
You can check the Object.keys documentation for more details, specifically, the examples section and the non-object coercion section, which state:
// simple array const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
and
In ES5, if the argument to this method is not an object (a
primitive), then it will cause a TypeError.From ES2015 onwards, a non-object argument will be coerced to an
object.// In ES5 Object.keys('foo'); // TypeError: "foo" is not an object
// In ES2015+ Object.keys('foo'); // ["0", "1", "2"]
Related Topics
Loop Through an Array in JavaScript
How to Create a File in Memory For User to Download, But Not Through Server
How to Trigger Event in JavaScript
How to Detect Safari, Chrome, Ie, Firefox and Opera Browsers
Sorting in JavaScript: Shouldn't Returning a Boolean Be Enough For a Comparison Function
What's the Meaning of "=≫" (An Arrow Formed from Equals & Greater Than) in JavaScript
How to Add a Delay in a JavaScript Loop
Window.Onload VS $(Document).Ready()
How to Make the First Letter of a String Uppercase in JavaScript
Creating Multiline Strings in JavaScript
How to Merge Two Arrays in JavaScript and De-Duplicate Items
Weird Behavior With Objects & Console.Log
Convert Date to Another Timezone in JavaScript