admin管理员组

文章数量:1326146

I am municating 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 pact way.

I am municating 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 pact way.

Share Improve this question edited Dec 9, 2015 at 20:25 Nina Scholz 387k26 gold badges363 silver badges413 bronze badges asked Dec 9, 2015 at 20:17 john doejohn doe 9,71023 gold badges94 silver badges176 bronze badges 1
  • 1 @Hexaholic This is a perfectly answerable specific programming question, as such I find it perfectly on-topic for Stack Overflow. – Simon Forsberg Commented Dec 9, 2015 at 20:29
Add a ment  | 

3 Answers 3

Reset to default 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);

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.

Fun with one-liners and ES6

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

http://jsfiddle/ya26m2dq/1/

本文标签: Concatenate Strings of Custom Object Array in JavaScriptStack Overflow