简体   繁体   English

连接多个对象的第一个字段

[英]Concatenate first fields of multiple objects

Is there a way in javascript to concatenate named/indexed fields (say one field of each object) of multiple objects to a string. 在javascript中是否有一种方法可以将多个对象的命名/索引字段(比如每个对象的一个​​字段)连接到字符串。

var theArray = [{
 field1: "TEXT",
 field2: "VAL"
 ...
},
{
 field1: "text",
 field2: "val"
 ...
}
...
];

I would like for the sake of ideomacy (ideomatic programming) to know if there's a way to concatenate values of all field1 in an array WITHOUT a for loop. 我想为了ideomacy(ideomatic编程)知道是否有一种方法来连接一个没有for循环的数组中所有field1值。

Something like 就像是

theArray.getFieldValues[0].join(', ');

Which options do we have here? 我们在这有哪些选择?

  • overload Array - wouldn't do that, 重载数组 - 不会这样做,
  • helper function - don't wanna loops. 辅助函数 - 不想循环。

There're filter and grep functions in jQuery, but they only filter the elements, I would like to know if there's already something like 在jQuery中有过滤器和grep函数,但它们只过滤元素,我想知道是否已经有类似的东西

theArray.grepNewObject(function(o){ return o.field1; }).join(', ');

You can use map first to get an array of just field1 and then join it: 您可以先使用map获取只是field1的数组,然后加入它:

theArray.map(function(x){return x.field1}).join(', ');

Note that map needs to be shimmed in IE 8 and earlier. 请注意,映射需要在IE 8及更早版本中进行填充。 Alternatively, since you're using jQuery, you can use jQuery.map for a cross-browser solution: 或者,由于您使用的是jQuery,因此您可以将jQuery.map用于跨浏览器解决方案:

$.map(theArray, function(x){return x.field1}).join(', ');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM