在JavaScript中连接自定义对象数组的字符串

时间:2015-12-09 20:17:25

标签: javascript

我正在与返回响应的Web服务进行通信。响应可以收集错误。我需要遍历集合并连接所有原因。这是代码:

var errorText = "";

for ( var i = 0; i < response.errors.count; i++ ) {
    errorText += response.errors[i].reason; 
}

这个有效!但我认为必须有一个更好的紧凑方式。

3 个答案:

答案 0 :(得分:6)

使用Array.prototype.mapArray.prototype.join

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:3)

一个foreach?

ssc.start()
      ssc.awaitTermination()
      val lines = messages.map(_._2)
      val words = lines.flatMap(_.split(" "))
      val wordCounts = words.map(x => (x, 1L)).reduceByKey(_ + _)
      wordCounts.print()

编辑:一些澄清。

foreach优于for循环,特别是因为JavaScript不强制执行连续的元素。

假设您的数组是这样的:var errorText = ""; response.errors.forEach(function(element) { errorText += element.reason; });

{1, 2, 3, undefined, 4, 5, 6, undefined, 7}循环显然会迭代,包括未定义的值,而for则不会。

注意,如果您正在使用对象而不是数组,则forEach将无效。你需要:

forEach

使用对象时,这比var errorText = ""; Object.keys(response.errors).forEach(function(key) { errorText += response.errors[key]; }); for要好得多。但是在这种情况下,我假设它是一个阵列,但我无法确定没有更多信息。

答案 2 :(得分:0)

单行和ES6的乐趣

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

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