'lodash: check object is empty

I have this object: {"": undefined}

and when I check this object for empty in this way: _.isEmpty({"": undefined})

I get false result, maybe in lodash we have another method?



Solution 1:[1]

_.isEmpty(obj, true)

var obj = {
  'firstName': undefined
, 'lastName' : undefined
};

console.log(_.isEmpty(obj)); // false
console.log(_.isEmpty({})); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Please, see http://www.ericfeminella.com/blog/2012/08/18/determining-if-an-object-is-empty-with-underscore-lo-dash/

Solution 2:[2]

It depends on how you want to check it. Do you want to check some or every

Then what you can do is :

import { some, isEmpty } from 'lodash'
console.log(some(this.yourObject, isEmpty))

Solution 3:[3]

In your case it cannot be called an empty object (Object.values(obj).length would return 1), but for a completely empty object this can be used:

import { matches } from 'lodash';
matches(obj, {});

Solution 4:[4]

I guess this is a bit overkill, but this is what I use which recursively checks for nested objects too and uses lodash.

function checkEmptyObject(obj) {
  if (_.isEmpty(obj)) return true;
  return _.isEmpty(
    Object.entries(obj)
      .map(([key, value]) => {
        if (_.isEmpty(value)) return true;
        if (value instanceof Object) return checkEmptyObject(value);
        return false;
      })
      .filter((b) => b === false)
  );
}

Solution 5:[5]

To provide an alternative to Lodash - this is how I do the same with vanilla JS ES6.

const isEmpty = (obj) => {
    return obj === undefined ? true : Object.keys(obj).length === 0
}

console.log(isEmpty(undefined))
console.log(isEmpty({}))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 danday74
Solution 2 pkerckhove
Solution 3 truefusion
Solution 4 soulphoenix
Solution 5 Hexodus