1

i have a method that returns an object that contains 4 objects:

function getFiles() {
    var documents = {};

    documents.files1ToBeCompleted = DocumentsService.getFiles1Uncompleted();
    documents.files2ToBeCompleted = DocumentsService.getFiles2Uncompleted();
    documents.files3ToBeCompleted = DocumentsService.getFiles3Uncompleted();
    documents.files4ToBeCompleted = DocumentsService.getFiles4Uncompleted();

    return documents;
}

I'm trying to use Underscore function ._isEmpty to verify if the object is empty, i mean the case in which i get an object with empty sub-objects. But even all its 4 objects are empty, it is not empty because it contains 4 items. Do you know any way to check if an object is "deep empty"?

smartmouse
  • 13,912
  • 34
  • 100
  • 166

2 Answers2

4

Here's what worked for me. It is recursive and takes care of all nested objects (uses lodash).

function isEmptyDeep(obj) {
  if(isObject(obj)) {
    if(Object.keys(obj).length === 0) return true
    return every(map(obj, v => isEmptyDeep(v)))
  } else if(isString(obj)) {
    return !obj.length
  }
  return false
}

It first checks if there are no keys, and returns true in that case.

Then it checks the keys and runs isEmptyDeep on each. If the value is an object (or array), it will continue recursion.

If there's an empty array or empty string, length will be 0 and will be considered empty.

If the value is 0, false, or other falsy values, then it would be considered not empty. If you want to consider falsey values as empty, this as the first line in the function above:

if(!obj) return true
Jake
  • 990
  • 1
  • 10
  • 17
-3

Thanks to Bergi that lead me to this working solution:

_.every(documentsObject, function(property) { return _.isEmpty(property); });

that returns true if the object is "deep empty", false otherwise.

smartmouse
  • 13,912
  • 34
  • 100
  • 166