2
{
    "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?

Isaac
  • 11,409
  • 5
  • 33
  • 45
Yunhee
  • 125
  • 1
  • 4
  • 11

3 Answers3

2

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
}
Juorder Gonzalez
  • 1,642
  • 1
  • 8
  • 10
1
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));
Isaac
  • 11,409
  • 5
  • 33
  • 45
0

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.

llama
  • 2,535
  • 12
  • 11