xxxxxxxxxx
function isEmptyObject(obj) {
// Check if object has any properties
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false; // Object has at least one property
}
}
return true; // Object is empty
}
// Example usage
var myObject = {};
console.log(isEmptyObject(myObject)); // Output: true
var anotherObject = { name: "John", age: 25 };
console.log(isEmptyObject(anotherObject)); // Output: false
xxxxxxxxxx
const empty = {};
/* -------------------------
Plain JS for Newer Browser
----------------------------*/
Object.keys(empty).length === 0 && empty.constructor === Object
// true
/* -------------------------
Lodash for Older Browser
----------------------------*/
_.isEmpty(empty)
// true
xxxxxxxxxx
const empty = {};
/* -------------------------
Plain JS for Newer Browser
----------------------------*/
Object.keys(empty).length === 0 && empty.constructor === Object
// true
/* -------------------------
Lodash for Older Browser
----------------------------*/
_.isEmpty(empty)
// true
xxxxxxxxxx
const emptyObject = {
}
// Using keys method of Object class
let isObjectEmpty = (object) => {
return Object.keys(object).length === 0;
}
console.log(isObjectEmpty(emptyObject)); // true
// Using stringify metod of JSON class
isObjectEmpty = (object) => {
return JSON.stringify(object) === "{}";
}
console.log(isObjectEmpty(emptyObject)); // true
xxxxxxxxxx
if(
objectName // Verify object presence
&& Object.keys(objectName).length === 0 // Verify object content
&& Object.getPrototypeOf(objectName) === Object.prototype // Verify object type
) {
// Run truthy condition.
}