{
"cd": {},
"person": {},
"p2": {
"foo1": {},
"foo2": {}
}
}
"cd"
doesn't have child object (empty object).
"p2"
has child object.
how to check if exists child object value?
{
"cd": {},
"person": {},
"p2": {
"foo1": {},
"foo2": {}
}
}
"cd"
doesn't have child object (empty object).
"p2"
has child object.
how to check if exists child object value?
For specific child name you can try this:
var object = {
"cd": {},
"person": {},
"p2": {
"foo1": {},
"foo2": {}
}
}
if (object.cd.hasOwnProperty("childName")) {
// Do some stuff here
}
if you are looking for any child into the object you can try this
const objectToCheckIfHasChildren = object.cd;
const children = Object.keys(objectToCheckIfHasChildren);
if (children.length > 0) {
// then children has at least one child
}
function hasChild(obj){
return !!Object.keys(obj).length;
}
var obj = {
"cd": {},
"person": {},
"p2": {
"foo1": {},
"foo2": {}
}
};
console.log(hasChild(obj.cd));
console.log(hasChild(obj.p2));
Here's a way that'll handle null
and undefined
as well.
function isEmpty(obj) {
for (const _ in obj) return false;
return true;
}
You can add a .hasOwnProperty()
check if you're worried about inherited, enumerable properties.
So an empty object, null
and undefined
will return true
(being empty), otherwise false
is returned.