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", }
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", }
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'));
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: