-1

I have this code. I need to write a validation for this object. if any of the property is empty or not a string console log an error or console log a message.

var obj = { ob1 : {"val1" : "test1", "val1" : "test1"},
            ob2 : ["v2", "v3", "v4"]
          };

for (var property in obj){
if (typeof obj[property] !=='string' || obj[property] === ""){
console.log(property + ' is empty or not a string!');
 }};

how do I write code or fiunction to ob1 and ob2.

  • 1
    SO is not a code-writing service. Please take the [tour] and review [ask]. – jonrsharpe Jun 21 '18 at 16:40
  • This same question was asked just a while ago ..? Not exactly the same but ... https://stackoverflow.com/questions/50954899/check-if-a-value-is-string-in-an-object-javascript – Teemu Jun 21 '18 at 16:40
  • Use the same code, but do it recursively. – Barmar Jun 21 '18 at 17:20

2 Answers2

0

You can use the constructor to check Whether it is a array of object and than simply iterate based on that and check each element.

var obj = { ob1 : {"val1" : "test1", "val2" : "test1"},
            ob2 : ["v2", "v3", ""]
          };
 var result = true;
 Object.keys(obj).forEach((key)=>{
  if(obj[key].constructor.toString().indexOf('Array') > 0){
    obj[key].forEach((element)=>{
      if(typeof element !=='string' || element === '')
        result = false;
    });
  }
  if(obj[key].constructor.toString().indexOf('Object') > 0){
    Object.keys(obj[key]).forEach((element)=>{
      if(typeof obj[key][element] !=='string' || element === '')
        result = false;
    });
   }
 });
if(!result)
  console.error('A property is not a string or empty!');
amrender singh
  • 7,949
  • 3
  • 22
  • 28
0

Maybe like this:

var obj = {
           ob1 : {
                   "val1" : "test1",
                   "val2" : "test2"
           },
           ob2 : [
                  "v2",
                  "v3",
                  "v4"
           ]
          };

for (var property in obj){
   if (typeof obj[property] !=='string' || obj[property] !== null){
     console.log(property + ' is NOT empty or not a string!');
      if(obj[property] instanceof Array){
         console.log(property + ' is Array');
         for(var ka in obj[property]){
           console.log(' array el ->'+obj[property][ka]);
         }
      }else if(typeof obj[property]==='object'){
         console.log(property + ' is object');
         for(var ko in obj[property]){
             console.log(' obj el ('+ko+') - >'+obj[property][ko]);
         }

      }

   }
};
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17