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

如何将List转换为指定格式的Map结构并得到目标结果?

问题:将List转换为指定格式的Map

期望输出

{"data":[{"id_pet":"63","id_habit":0},{"id_pet":"64","id_habbit":0}]}

现有数据与代码

原始List数据

↓   pet: List (2 items)
  ↓ [0]: Pet
    id_pet: 1
    id_habbit: 1
  ↓ [1]: Pet
    id_pet: 2
    id_habbit: 2

当前使用的代码

event.listPet.asMap();

正确转换方法

asMap()仅会生成以列表索引为键、元素为值的Map,完全不符合需求。你需要分两步处理:

  1. 遍历List<Pet>,将每个Pet对象转换为目标格式的Map(注意id_pet要转为字符串,id_habbit可按需固定为0或保留原数值)
  2. 将转换后的列表包裹在data键下,得到最终结构

代码实现

如果需要将id_habbit固定为0:

// 转换每个Pet为目标Map
final convertedPets = event.listPet.map((pet) => {
  'id_pet': pet.id_pet.toString(),
  'id_habbit': 0,
}).toList();

// 生成最终结果Map
final result = {'data': convertedPets};

如果需要保留原id_habbit的值:

final convertedPets = event.listPet.map((pet) => {
  'id_pet': pet.id_pet.toString(),
  'id_habbit': pet.id_habbit,
}).toList();

final result = {'data': convertedPets};

注意:目标输出里存在拼写不一致(id_habit和id_habbit),请根据实际需求调整键名。

内容的提问来源于stack exchange,提问作者Ahmed Salavy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:15:31