You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为多级集合的每个子集合添加序号字段?

解决方案

你可以用Groovy的collectWithIndex方法来实现,它能在遍历集合时同时获取元素和对应的索引,并且返回新的集合,刚好满足给每个子集合(Map)添加序号的需求:

代码示例

// 原集合
def originalList = [
    [Name: 'John', City: 'London'],
    [Name: 'Rachel', City: 'Paris']
]

// 生成带序号的新集合
def numberedList = originalList.collectWithIndex { item, index ->
    // 将序号Map与原子集合合并,序号从1开始
    [Number: index + 1] + item
}

// 输出结果
println numberedList

执行后得到的结果就是你需要的:

[
    [Number:1, Name:John, City:London],
    [Number:2, Name:Rachel, City:Paris]
]

另一种方式:修改原集合

如果你不需要保留原集合,也可以用eachWithIndex直接修改每个子集合的内容:

originalList.eachWithIndex { item, index ->
    // 给每个子集合添加Number键值对
    item.Number = index + 1
}

这种方式会直接修改原集合中的元素,不需要创建新集合。

内容的提问来源于stack exchange,提问作者Hanan Cohen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:45:30