3

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.

1
  • 1
    @Hexaholic This is a perfectly answerable specific programming question, as such I find it perfectly on-topic for Stack Overflow. Commented Dec 9, 2015 at 20:29

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

i would add a space between.
1

Fun with one-liners and ES6

const errorText = response.errors.map(err => err.reason).join(" ");

http://jsfiddle.net/ya26m2dq/1/

1 Comment

your answer best

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.