-4

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 = { "val1" : "test1", "val1" : "test1", "val1" : "test1", }

Ayoob Nazeer
  • 9
  • 1
  • 4
  • Possible duplicate of [Check if a variable is a string in JavaScript](https://stackoverflow.com/questions/4059147/check-if-a-variable-is-a-string-in-javascript) – Virmundi Jun 20 '18 at 18:32
  • `if(Object.values(obj).some(el => !el)) console.error("sth");` – Jonas Wilms Jun 20 '18 at 18:32
  • This is a duplicate. Look at the older one. Apply it to an iterative form over the properties of the object. – Virmundi Jun 20 '18 at 18:33
  • 3
    Possible duplicate of [How do you check for an empty string in JavaScript?](https://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – Heretic Monkey Jun 20 '18 at 18:33

2 Answers2

0

You can pretty easily check if something is a string or not. This code loops through the properties and checks if the value of each key is a string or not. I am doing simple printing but you can do more based on what you want your program to do.

let obj = { "val1" : "test1", "val2" : "test1", "val3" : 4, }

Object.keys(obj)
  .map(e => typeof(obj[e]) === 'string' ? console.log('string') : console.log('not string'));
chevybow
  • 9,959
  • 6
  • 24
  • 39
0

Here's an approach that might be easier to understand.

This code logs an error if one or more properties are not a string:

var obj = {
  "val1": "test1",
  "val2": 1,
  "val3": null
};

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

PS: You had some errors in your code:

  • Don't add a comma after the last property, it may lead to errors
  • You have overwritten the same property over and over again
  • You where missing a semicolon after the closing curly bracket of your object, may also lead to errors
CodeF0x
  • 2,624
  • 6
  • 17
  • 28
  • Thank you it worked. Instead of making the output as 1 is not a number I want to to have "val3 is not a number". – Ayoob Nazeer Jun 20 '18 at 20:45
  • @AyoobNazeer Please take a look at my updated answer. It now displays `val2` (and so on) instead of the value. – CodeF0x Jun 20 '18 at 20:52