javascript - how to check if exists child object value of key in object?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 | { "cd": {}, "person": {}, "p2": { "foo1": {}, "foo2": {} } } |
对于特定的子名称,可以尝试以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 | var object = { "cd": {}, "person": {}, "p2": { "foo1": {}, "foo2": {} } } if (object.cd.hasOwnProperty("childName")) { // Do some stuff here } |
如果您在对象中查找任何子对象,可以尝试此操作
1 2 3 4 5 6 | const objectToCheckIfHasChildren = object.cd; const children = Object.keys(objectToCheckIfHasChildren); if (children.length > 0) { // then children has at least one child } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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)); |
这是一种处理
1 2 3 4 | function isEmpty(obj) { for (const _ in obj) return false; return true; } |
您可以添加一个
所以一个空的对象,