csv - How to output an array to a comma-deliniated string?
问题描述
I have an array called device
, which looks like this (simplified):
label : "Device 1",
exhibits : [{
item : 1,
desc : "This is a sample"
},{
item : 2,
desc : "This is another sample"
},{
item : 3,
desc : "This is a third"
}]
I'm trying to print exhibits
neatly for a PDF, so I'm thinking comma-deliniated like this:
1, 2, 3
This is my code:
<cfloop array="#device.exhibits#" index="exhibit">
#exhibit.item#
</cfloop>
But I get this:
123
Yes, I could manually figure out if there should be commas or not, but is there a better way to do this?
解决方案
由于您使用的是 CF11+,因此您可以使用ArrayMap
带有 an 的函数ArrayList
将数组转换为列表。
exhibits.map( function(i) { return i.item ; } ).toList() ;
使用您的示例数组,它会为您提供“ 1,2,3
”。
在我的另一个答案中,我逐步处理了空元素。由于这是一个结构数组,我不知道这是否会成为问题。您如何为您的exhibits
阵列获取这些数据?
编辑:
exhibits.map( function(i) { return i.item ; } )
.filter( function(j) { return len(j) ; } )
.toList() ;
将返回删除了空元素的列表。
编辑2:
根据@TravisHeeter 的问题,如果您更喜欢 lambda 表达式或箭头函数,您可以在 Lucee 5 中使用它们。
exhibits.map( (i) => i.item ).filter( (j) => len(j) ).toList()
https://trycf.com/gist/907a68127ddb704611b191d494aa94ce/lucee5?theme=monokai
推荐阅读
- java - Java 套接字服务器发送大文件
- ms-access - Ms Access 需要根据同一个表字段的多个条件进行计算
- sql - 无效号码 ORA-01722
- google-apps-script - 为 onLoad 事件优化 Google Sheets 函数
- c# - 如何从 SQL Server 向 gmail 发送电子邮件
- python - 数据框的所有组合,按 ID 分组并按升序元素排序
- c# - Windows C# 窗体:如何在按钮上显示具有透明背景的 GIF 动画?
- node.js - 如何同时使用redis和sequelize
- php - 需要通过 PHP 解析未过滤的 url 查询,无法处理 '&' 符号
- typescript - 如何在打字稿中调用两个连续的rest api?