0

Trying to find a short, concise and an efficient way of checking nulls or empty values in an object coming from a user.

The naive way is to have several if and else, the other way I'm attempting is passing keys but then I can't check for nested objects.

naive way

var data = {};
if(data != null && data.username != null && data.first != null && data.last != null && data.department != null) { 
}

using for loop

var data = {};
["first", "last", "email", "dept"].map(function (key) {
    if(data[key] == null || data[key] == "") 
        console.log("reject"); 
});

What about nested objects?

var data = {};
["dept", "dept.id", "dept.name"].map(function (key) {
    if(data[key] == null || data[key] == "") 
        console.log("reject"); 
});
AppDeveloper
  • 1,816
  • 7
  • 24
  • 49
  • 1
    Your implementations are different - first one rejects if all fields are null, the second one - for any null field. You can probably better use `Array.prototype.every`/`Array.prototype.some` in this cases. To check nested objects you can use something like `lodash.get()` instead: `const isEmpty = value => [ null, '', undefined ].includes(value); const get = (object, path) => path.split('.').reduce((result, key) => result && result[key], object); const hasEmptyFields = (object, paths) => paths.some(path => isEmpty(get(object, path)));` – Andres Oct 09 '19 at 08:20
  • Thanks, this is elegant. – AppDeveloper Oct 09 '19 at 08:53

0 Answers0