if I have an array like this:
var msg = [ {name: ["a1", "a2"], value: "this is A"},
{name: ["b1", "b2"], value: "this is B"},
...
]
The array contains global errors messages for client-side form validations. I have managed to pass in faulty inputs (e.g. “a1”) and now am wondering how to get the corresponding message out of my ill-constructed array.
Question
What would be the best way to loop through this array? for example, if I have “a1” as parameter passed into my function, how do I extract “this is A” as corresponding message?
inArray doesn’t really help, because I need the corresponding message and not the position of a1. I’m also not sure if this is the best way to store my error messages… ideas welcome!
Thanks for help!
Re-arrange your data structure:
This makes it really easy to set up new error codes and messages, and is extremely easy to understand. The only gotcha is
error_codes[my_param]– it’s an object, but we can’t doerror_codes.my_parambecause it’ll look for the element called ‘my_param’, so using array notation, we can look up the object key.The only other potential trap is making sure you don’t have any trailing commas:
Also knows as the trailing comma of death!