103

What is the most elegant way to determine if all attributes in a javascript object are either null or the empty string? It should work for an arbitrary number of attributes.

{'a':null, 'b':''} //should return true for this object
{'a':1, 'b':''} //should return false for this object
{'a':0, 'b':1} //should return false
{'a':'', 'b':''} //should return true
Sampath
  • 63,341
  • 64
  • 307
  • 441
J-bob
  • 8,380
  • 11
  • 52
  • 85
  • 1
    No matter what, you'll have to loop through all the elements in the object and check each one. – wmock Dec 30 '14 at 17:21

20 Answers20

189

Check all values with Object.values. It returns an array with the values, which you can check with Array.prototype.every or Array.prototype.some:

const isEmpty = Object.values(object).every(x => x === null || x === '');
const isEmpty = !Object.values(object).some(x => x !== null && x !== '');
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
PVermeer
  • 2,631
  • 2
  • 10
  • 18
  • 7
    or shorter: Object.values(object).every(x => !!x); – Jonathan Meguira Jan 29 '20 at 16:26
  • 1
    @JonathanMeguira This is not what the OP is asking for. Checking for falsy includes way more then an empty string or null. – PVermeer Mar 09 '20 at 13:47
  • 2
    @abd995 That’s not correct. `some` and `every` are _equally_ efficient and equally fast. They both implement short-circuit evaluation: as soon as `some` hits a value for which the condition doesn’t hold, the iteration stops, yes, but the same thing applies to `every`. – Sebastian Simon May 28 '21 at 22:22
  • 1
    `array.some(Boolean)` & `array.every(Boolean)` excels here, too. (be mindful of `0`'s though). – darcher Apr 25 '23 at 11:52
79

Create a function to loop and check:

function checkProperties(obj) {
    for (var key in obj) {
        if (obj[key] !== null && obj[key] != "")
            return false;
    }
    return true;
}

var obj = {
    x: null,
    y: "",
    z: 1
}

checkProperties(obj) //returns false
Community
  • 1
  • 1
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 2
    @ J-Bob: This or adeneo's answer should get you started. If you also want to allow `undefined`, change the `=== null` to `== null`. And you may or may not want to add a `hasOwnProperty` check, depending on whether you care about properties from prototypes. (adeneo's answer only checks "own" properties, tymeJV's does both "own" and prototype). Or perhaps a check ignoring properties referring to functions (again, if desired). – T.J. Crowder Dec 30 '14 at 17:27
30

Here's my version, specifically checking for null and empty strings (would be easier to just check for falsy)

function isEmptyObject(o) {
    return Object.keys(o).every(function(x) {
        return o[x]===''||o[x]===null;  // or just "return o[x];" for falsy values
    });
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
14
let obj = { x: null, y: "hello", z: 1 };
let obj1 = { x: null, y: "", z: 0 };

!Object.values(obj).some(v => v);
// false

!Object.values(obj1).some(v => v);
// true
Gaurav Arya
  • 211
  • 3
  • 7
  • 4
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – β.εηοιτ.βε May 23 '20 at 22:13
10

Quick and simple solution:

Object.values(object).every(value => !!value);
Amaresh C.
  • 579
  • 5
  • 17
9

Using Array.some() and check if the values are not null and not empty is more efficient than using Array.every and check it the other way around.

const isEmpty = !Object.values(object).some(x => (x !== null && x !== ''));

This answer should just make the excellent comment of user abd995 more visible.

deamon
  • 89,107
  • 111
  • 320
  • 448
6

You can use the Array.reduce prototype on your object's keys.

Assuming that the object is structured as follows:

var obj = {
    x: null,
    y: "",
    z: 1
}

you can use the following instruction to discover if all of it's properties are unset or set to empty string using just one line:

Object.keys(obj).reduce((res, k) => res && !(!!obj[k] || obj[k] === false || !isNaN(parseInt(obj[k]))), true) // returns false

If you want to discover if all of it's properties are set instead you have to remove the negation before the conditions and set the initial result value to true only if the object has keys:

Object.keys(obj).reduce((res, k) => res && (!!obj[k] || obj[k] === false || !isNaN(parseInt(obj[k]))), Object.keys(obj).length > 0) // returns false as well
whirmill
  • 135
  • 2
  • 7
5

Based on adeneo's answer, I created a single line condition. Hope it will be helpful to someone.

var test = {
  "email": "test@test.com",
  "phone": "1234567890",
  "name": "Test",
  "mobile": "9876543210",
  "address": {
      "street": "",
      "city": "",
      "state": "",
      "country": "",
      "postalcode": "r"
  },
  "website": "www.test.com"
};

if (Object.keys(test.address).every(function(x) { return test.address[x]===''||test.address[x]===null;}) === false) {
   console.log('has something');
} else {
   console.log('nothing');
}

You can test it https://jsfiddle.net/4uyue8tk/2/

ajilpm
  • 217
  • 1
  • 3
  • 7
5

Just complementing the past answers: they'll work if your object doesn't contain arrays or objects. If it does, you'll need to do a 'deep check'.

So I came up with this solution. It'll evaluate the object as empty if all its values (and values inside values) are undefined, {} or [].

function deepCheckEmptyObject(obj) {
    return Object.values(obj).every( value => {
        if (value === undefined) return true;
        else if ((value instanceof Array || value instanceof Object) && _.isEmpty(value) ) return true;
        else if (value instanceof Array && !_.isEmpty(value)) return deepCheckEmptyArray(value);
        else if (value instanceof Object && !_.isEmpty(value)) return deepCheckEmptyObject(value);
        else return false;
    });
}

function deepCheckEmptyArray(array) {
    return array.every( value => {
        if (value === undefined) return true;
        else if ((value instanceof Array || value instanceof Object) && _.isEmpty(value)) return true;
        else if (value instanceof Array && !_.isEmpty(value)) return deepCheckEmptyArray(value);
        else if (value instanceof Object && !_.isEmpty(value)) return deepCheckEmptyObject(value);
        else return false;
    });
}

Note it uses Lodash's .isEmpty() to do the heavy work after we 'isolated' a value. Here, Lodash is imported as '_'.

Hope it helps!

Bruno Ribeiro
  • 646
  • 6
  • 13
4

Also if you are searching for only values are empty within the object,

Object.values({ key: 0, key2: null, key3: undefined, key4: '' }).some(e => Boolean(e))
// false

Object.values({ key: 0, key2: null, key3: undefined, key4: "hello" }).some(e => Boolean(e))
// true

Object.values({ key: 1, key2: "hello" }).some(e => Boolean(e))
// true
2

Based on tymeJv's answer =)

function checkProperties(obj) {
var state = true;
  for (var key in obj) {
    if ( !( obj[key] === null || obj[key] === "" ) ) {
        state = false;
        break;
    }
  }
  return state;
}

var obj = {
  x: null,
  y: "",
  z: 1
}

checkProperties(obj) //returns false

Hope it helps =)

Luis García
  • 58
  • 1
  • 6
2

This will give you all the keys from the object which is empty, undefined and null

Object.keys(obj).filter((k)=> {
  if (obj[k] === "" || obj[k]===undefined || obj[k]===null) {
    return k;
  }
});
Jeevan K.A
  • 21
  • 1
1

Building on top of other answers I would use lodash to check isEmpty on the object, as well as its properties.

const isEmpty = (object) => return _.isEmpty(object) || !Object.values(object).some(x => !_.isEmpty(x))
mkapiczy
  • 325
  • 3
  • 11
0

This skip the function attribute

function checkIsNull(obj){
  let isNull=true;
  for(let key in obj){
   if (obj[key] && typeof obj[key] !== 'function') {
    isNull = false;
   }
  }
  return isNull;
 }

var objectWithFunctionEmpty={
  "name":undefined,
  "surname":null,
  "fun": function (){ alert('ciao'); }
}

var objectWithFunctionFull={
  "name":undefined,
  "surname":"bla bla",
  "fun": function (){ alert('ciao'); }
}

checkIsNull(objectWithFunctionEmpty); //true
checkIsNull(objectWithFunctionFull); //false
Alessandro
  • 284
  • 4
  • 13
0

This works with me perfectly:

checkProperties(obj) {
  let arr = [];
  for (let key in obj) {
    arr.push(obj[key] !== undefined && obj[key] !== null && obj[key] !== "");
  }
  return arr.includes(false);
}

This will return true or false if there is at-least one value is empty or something like that.

nael_d
  • 27
  • 1
  • 11
0

You can use Object.values() method to get all the object's values (as an array of object's values) and then check if this array of values contains null or "" values, with the help of _.includes method prvided by lodash library.

const checkObjectProperties = obj => {
  const objValues = Object.keys(obj);

  if (_.includes(objValues, "") || _.includes(objValues, null)) {
    return false;
  } else {
    return true
  }
  
  const incorrectObjProps = { one: null, two: "", three: 78 }
  const correctObjProps = { one: "some string" }
  
  checkObjectProperties(incorrectObjProps) // return false
  checkObjectProperties(correctObjProps) // return true
}
Hamza Hmem
  • 502
  • 5
  • 11
0

I'll add my two sense:

Object.values(object).every(value => Boolean(value));
Richard Oliver Bray
  • 1,043
  • 13
  • 20
  • 1
    this wont allow whitespaces also => `var stateIsValid = Object.values(this.state).every((value) => Boolean(String(value).trim()))` – Gambitier Jul 16 '21 at 11:10
0

Solution:

function checkValues(obj) {
  var objValues = Object.values(obj);
  if (objValues.length < 1) return false;
  return objValues.every((value) => {
    if (value === null) return true;
    if (typeof(value) == 'string')
      if(!(value || false))
        return true;
    return false;
  });
}
// OR
Object.values( obj ).every(
  value => value === null || (typeof(value) == 'string' && !(value || false))
);

Testing:

checkValues({ a: null, b: '' });
// OR
Object.values({ a: null, b: '' }).every(
  value => value === null || (typeof(value) == 'string' && !(value || false))
);
// Output: true

checkValues({ a: '', b: '' });
// OR
Object.values({ a: '', b: '' }).every(
  value => value === null || (typeof(value) == 'string' && !(value || false))
);
// Output: true

checkValues({ a: 0, b: '' });
// OR
Object.values({ a: 0, b: '' }).every(
  value => value === null || (typeof(value) == 'string' && !(value || false))
)
// Output: false

checkValues({ a: 0, b: 1 });
// OR
Object.values({ a: 0, b: 1 }).every(
  value => value === null || (typeof(value) == 'string' && !(value || false))
)
// Output: false

checkValues({ a: 1, b: '' });
// OR
Object.values({ a: 1, b: '' }).every(
  value => value === null || (typeof(value) == 'string' && !(value || false))
)
// Output: false
dimankiev
  • 76
  • 1
  • 3
0

You can use the Object.values() method to get all of the object's values (as an array of object's values) and then check if this array of values contains null or "", with the help of methods provided by the lodash library.

Infigon
  • 554
  • 5
  • 18
Patriarch
  • 1
  • 1
-1

How about this?

!Object.values(yourObject).join('')