1

I have an object that has other objects inside it up to n levels. I want to check if the object only contains other objects. Like this:

var emptyObj = {
    obj1 : {
        obj1a : {},
        obj1b : {}
    },
    obj2 : {},
    obj3 : {
        obj3a : {
            obj3aa : {}
        }
    }
};

Changing the data structure is not an option. No jQuery.

-- edit--

If there is anything apart from an empty object {} at the last level, the test should fail. Failure examples:

var notEmpty1 = {
    obj1 : []
};
var notEmpty2 = {
    obj1: {
        obj1a: ""
    },
    obj2: {}
};
5
  • 1
    The answer is: recursion. Commented Sep 12, 2015 at 2:36
  • please clarify, I can write recursive function but I don't understand the question Commented Sep 12, 2015 at 2:37
  • @WhiteHat I think he wants to check that the properties of the object are: not arrays, functions etc. Just objects. Commented Sep 12, 2015 at 2:39
  • Sorry, after reading the post again I realized it was not clear. There should be only empty objects at the leaf level. Commented Sep 12, 2015 at 2:48
  • @maow Not sure I said it's the only possible answer. Commented Sep 12, 2015 at 7:04

1 Answer 1

3

An object is empty if it's, well, an object, and every one of its keys is in turn an empty object.

function empty(o) {

  function isObject()      { return o && o.constructor === Object; }
  function keyEmpty(key)   { return empty(o[key]; }
  function everyKeyEmpty() { return Object.keys(o) . every(keyEmpty); }

  return isObject() && everyKeyEmpty();
}

Note that if an object has zero keys then "every" one of the zero keys passes the condition.

Sign up to request clarification or add additional context in comments.

3 Comments

Very good solution. I changed the second line to return true when !o, so {key: undefined} is understood as {}
Do really want {key: undefined} to be treated as empty? Actually, there's a subtle difference.
Yes, it is different, you are right. Your solution fits the answer as it was asked perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.