I am communicating with a web service which returns a response. The response can have errors collection. I need to iterate through the collection and concatenate all the reasons. Here is the code:
var errorText = "";
for ( var i = 0; i < response.errors.count; i++ ) {
errorText += response.errors[i].reason;
}
This works! But I am thinking there has to be a better compact way.
Use Array.prototype.map and Array.prototype.join
var response = {
errors: [{
reason: 'invalid username'
}, {
reason: 'invalid password'
}, {
reason: 'required field'
}]
};
var errorText = response.errors.map(function(errorObject) {
return errorObject.reason;
}).join('');
/*with shorter ES6 syntax
var errorText = response.errors.map(errorObject => errorObject.reason).join('');
*/
console.log(errorText);
A foreach?
var errorText = "";
response.errors.forEach(function(element) {
errorText += element.reason;
});
Edit: Some clarification.
A foreach is better than a for loop especially because JavaScript does not enforce contiguous elements.
Assuming your array is as such: {1, 2, 3, undefined, 4, 5, 6, undefined, 7}
A for loop would obviously iterate including the undefined values, where a forEach would not.
Note, if you're working with an object instead of an array, a forEach will not work. You will instead need:
var errorText = "";
Object.keys(response.errors).forEach(function(key) {
errorText += response.errors[key];
});
This is much better than for or for ... in when working with Objects. however in this case I'm assuming it's an array, but I can't know for sure without more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With