Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Last active January 16, 2020 01:48
Show Gist options
  • Save joe-oli/5e339cbe08d30bd78857951d6c7bd63f to your computer and use it in GitHub Desktop.
Save joe-oli/5e339cbe08d30bd78857951d6c7bd63f to your computer and use it in GitHub Desktop.
Does JS object have properties?
function objectHasProperties(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return true;
}
}
return false;
}
// ALT for more modern JS
if (Object.keys(obj).length > 0 )
return true;
else
return false;
//ALT #2. see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames
var propsArray = Object.getOwnPropertyNames(obj)
/*
Diff is Whether the returned list includes the non-enumerable properties: Object.keys() does not return them, while Object.getOwnPropertyNames() does.
var x = ["a", "b", "c", "d"];
Object.keys(x); //[ '0', '1', '2', '3' ]
Object.getOwnPropertyNames(x); //[ '0', '1', '2', '3', 'length' ]
--
Object.getOwnPropertyNames(a) returns all own properties of the object a.
Object.keys(a) returns all enumerable own properties.
It means that if you define your object properties without making some of them enumerable: false ,
these two methods will give you the same result.
It's easy to test:
var a = {};
Object.defineProperties(a, {
one: {enumerable: true, value: 'one'},
two: {enumerable: false, value: 'two'},
});
Object.keys(a); // ["one"]
Object.getOwnPropertyNames(a); // ["one", "two"]
If you define a property without providing property attributes descriptor (meaning you don't use Object.defineProperties), for example:
a.test = 21;
then such property becomes an enumerable automatically and both methods produce the same array.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment