Skip to content Skip to sidebar Skip to footer

Check If A Value Is String In An Object Javascript

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'

Solution 1:

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

Solution 2:

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'));

Post a Comment for "Check If A Value Is String In An Object Javascript"