首页 > 解决方案 > 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?

标签: csvcoldfusioncoldfusion-2016

解决方案


由于您使用的是 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


推荐阅读