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
3 Answers
Reset to default 6Use 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
版权声明:本文标题:Concatenate Strings of Custom Object Array in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742190386a2430102.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论