This is my obj, I just want to loop through this and show the errors:
var obj = {
"error": {
"errors": {
"username": {
"properties": {
"message": "username field is empty.",
"type": "required",
"path": "username"
},
"kind": "required",
"path": "username"
},
"email": {
"properties": {
"message": "email field is empty.",
"type": "required",
"path": "email"
},
"kind": "required",
"path": "email"
},
"password": {
"properties": {
"message": "password field is empty.",
"type": "required",
"path": "password"
},
"kind": "required",
"path": "password"
}
},
"_message": "User validation failed",
"message": "User validation failed: username: username field is empty., email: email field is empty., password: password field is empty."
}
}
I want to show the errors: properties.message but I'm having hard time, this is what I tried so far:
for (var key in obj.error.errors) {
for (var key2 in key.properties){
for (var key3 in key2.message){
console.log(key3)
}
}
}
But the console is blank.
-
something looks wrong with your 2nd and 3rd for loop :)Ji aSH– Ji aSH2020年07月22日 06:18:17 +00:00Commented Jul 22, 2020 at 6:18
3 Answers 3
In the loop you are getting the key, not the object itself. Also you don't need to add all those loops if your data is structured like that. Just pick the errors, iterate through all.
for(var d in obj.error.errors){
console.log(a[d].properties.message)
}
Sign up to request clarification or add additional context in comments.
Comments
a working solution
Object.values(obj.error.errors).forEach((error) => { console.log(error.properties.message) })
Looking to your data structure, you only need to iterate on the 'errors' list
answered Jul 22, 2020 at 6:20
Ji aSH
3,4841 gold badge12 silver badges20 bronze badges
Comments
Check this out, it will return you in the properties:message format
const obj = {
"error": {
"errors": {
"username": {
"properties": {
"message": "username field is empty.",
"type": "required",
"path": "username"
},
"kind": "required",
"path": "username"
},
"email": {
"properties": {
"message": "email field is empty.",
"type": "required",
"path": "email"
},
"kind": "required",
"path": "email"
},
"password": {
"properties": {
"message": "password field is empty.",
"type": "required",
"path": "password"
},
"kind": "required",
"path": "password"
}
},
"_message": "User validation failed",
"message": "User validation failed: username: username field is empty., email: email field is empty., password: password field is empty."
}
};
const objVal = Object.values(obj.error.errors);
const errors = objVal.reduce((obj, item) => {
return (obj[item.path] = item.properties.message, obj)
},{})
console.log(errors);
answered Jul 22, 2020 at 6:58
Rohit Ambre
9611 gold badge11 silver badges26 bronze badges
Comments
lang-js