Jessie Anderson
Jessie Anderson

Reputation: 319

All object property is not empty javascript

How to check the following object, make sure every property is not equal to undefined, null or empty string?

userObj = {
        name: {
            first: req.body.first,
            last: req.body.last
        },
        location: {
          city: req.body.city
        },
        phone: req.body.phone
    }

I can check req.body one by one like if(req.body.first) but that's too tedious if I have many params.

Upvotes: 0

Views: 342

Answers (5)

cнŝdk
cнŝdk

Reputation: 32145

You can simply use Array.prototype.some() method over Object.values() to implement this in a recursive way:

function isThereAnUndefinedValue(obj) {
  return Object.values(obj).some(function(v) {
    if (typeof v === 'object'){
      if(v.length && v.length>0){
          return v.some(function(el){
              return (typeof el === "object") ? isThereAnUndefinedValue(el) : (el!==0 && el!==false) ? !el : false;
          });
      }
      return isThereAnUndefinedValue(v);
    }else {
      console.log(v);
      return (v!==0 && v!==false) ? !v : false;
    }
  });
}

In the following function we will:

  • Loop over our object values.
  • Check if the iterated value is an object we call the function recursively with this value.
  • Otherwise we will just check if this is a truthy value or not.

Demo:

This is a working Demo:

userObj = {
  name: {
    first: "req.body.first",
    last: [5, 10, 0, 40]
  },
  location: {
    city: "req.body.city"
  },
  phone: "req.body.phone"
}

function isThereAnUndefinedValue(obj) {
  return Object.values(obj).some(function(v) {
    if (typeof v === 'object'){
      if(v.length && v.length>0){
          return v.some(function(el){
              return (typeof el === "object") ? isThereAnUndefinedValue(el) : (el!==0 && el!==false) ? !el : false;
          });
      }
      return isThereAnUndefinedValue(v);
    }else {
      console.log(v);
      return (v!==0 && v!==false) ? !v : false;
    }
  });
}

console.log(isThereAnUndefinedValue(userObj));

You will get a function that validates every object and its sub objects in a recursive way.

Upvotes: 1

SPlatten
SPlatten

Reputation: 5750

In your post you use:

    if(req.body.first)

I don't know if you are checking req and body before hand, but this should be:

    if ( typeof req == "object" && typeof req.body == "object"
    && req.body.first ) {

That is a safer way to check before use.

Or, if you want to embed in the object:

    function fnTest(a,b,c) {
        return (typeof a == "object" && typeof b == "object" && c) ? c : "";
    };

    userObj = {name:{
                first: fnTest(req, req.body, req.body.first)
                ,last: fnTest(req,req.body, req.body.last)
               },location:{
                city: fnTest(req,req.body,req.body.city)
               },phone: fnTest(req.body.phone)
              };

Upvotes: 0

marvel308
marvel308

Reputation: 10458

you can use the following validator to check, it works for a nested object as well

function objectValidator(obj){
	let ret = true;
	for(property in obj){
		//console.log(property, obj[property], typeof obj[property]);
		if(typeof obj[property] == "object"){
			if(obj[property] instanceof Array){
				ret = (ret & true);
			}
			else if(obj[property] == null){
				ret = false;
			}
			else{
				ret = (ret & objectValidator(obj[property]));
			}
		}
		else if(typeof obj[property] == "string"){
			if(obj[property] == ""){
				ret = false;
			}
		}
		else if(typeof obj[property] == "undefined"){
			ret = false;
		}
	}
	return ret;
}

let a = {
	b : 1,
	c :{
		d: 2,
		e: [3, 4],
		f : ""
	}
}
console.log(objectValidator(a));

Upvotes: 0

Ebrahim Poursadeqi
Ebrahim Poursadeqi

Reputation: 1816

you can create a simple validator for yourself like function below

var body = {
  a: 1,
  b: 3
};
var keys = ['a', 'b', 'c'];


function validate(body, keys) {
  for (var i in keys) {
    if (!body[keys[i]]) {
      return false;
    }
  }
  return true;
}

console.log(validate(body, keys));

Upvotes: 0

PeterMader
PeterMader

Reputation: 7275

To check for truthy values (values other than false, '', 0, null, undefined):

const hasOnlyTruthyValues = obj => Object.values(obj).every(Boolean);

Example:

const hasOnlyTruthyValues = obj => Object.values(obj).every(Boolean);
const object = {
  a: '12',
  b: 12,
  c: ''
};

console.log(hasOnlyTruthyValues(object));

The example you posted (if (res.body.first) ...) also checks for a truthy value. If you want to allow false and 0 (which are falsy, but you didn't mention them in your question), use:

const hasOnlyAllowedValues = obj => Object.values(obj).every(v => v || v === 0 || v === false);

Upvotes: 0

Related Questions