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

在Dart(Flutter)中为匹配列表ID的JSON对象添加新键的方法

问题描述

我有如下JSON数据:

{
    "result": [
        {
            "id": 2,
            "e_id": 2,
            "e_name": "0",
            "abc": 0,
            "doa": "2021-02-15 13:17:11"
        },
        {
            "id": 3,
            "e_id": 22,
            "e_name": "ok",
            "abc": 1,
            "doa": "2021-02-15 13:17:57"
        }
    ],
    "status": 1,
    "msg": "Successfully fetched"
}

以及一个匹配列表:

[2,1,5]

需求是给JSON中result数组里id存在于该列表的对象添加新键,预期结果如下:

{
    "result": [
        {
            "id": 2,
            "e_id": 2,
            "e_name": "0",
            "abc": 0,
            "doa": "2021-02-15 13:17:11",
            "added_key": "added value because the id number 2 is matched from the list array"
        },
        {
            "id": 3,
            "e_id": 22,
            "e_name": "ok",
            "abc": 1,
            "doa": "2021-02-15 13:17:57"
        }
    ],
    "status": 1,
    "msg": "Successfully fetched"
}

我尝试了以下代码,但存在问题:

List list = [2,1,5];
for (var i = 0;i < list.length; i++) {
  int aa = data.indexWhere((item) => item["id"] == list[i]);
  data[aa]["added_key"] = "added value";
}

请问如何用Dart正确实现这个需求?

解决方案

你的原有代码存在两个问题:

  1. 当列表中的id在result里不存在时,indexWhere会返回-1,此时访问data[-1]会直接报错
  2. 循环方向不合理,遍历result数组而非匹配列表,效率更高也更安全

以下是正确的实现代码:

import 'dart:convert';

void main() {
  // 模拟原始JSON字符串
  String jsonStr = '''
  {
      "result": [
          {
              "id": 2,
              "e_id": 2,
              "e_name": "0",
              "abc": 0,
              "doa": "2021-02-15 13:17:11"
          },
          {
              "id": 3,
              "e_id": 22,
              "e_name": "ok",
              "abc": 1,
              "doa": "2021-02-15 13:17:57"
          }
      ],
      "status": 1,
      "msg": "Successfully fetched"
  }
  ''';

  // 解析JSON为Dart可操作的Map结构
  Map<String, dynamic> jsonData = jsonDecode(jsonStr);
  List<dynamic> resultList = jsonData['result'];
  
  // 将匹配列表转为Set,提升查找效率(数据量大时优势明显)
  Set<int> targetIds = {2, 1, 5};

  // 遍历result数组,为符合条件的对象添加新键
  for (var item in resultList) {
    int itemId = item['id'];
    if (targetIds.contains(itemId)) {
      item['added_key'] = "added value because the id number $itemId is matched from the list array";
    }
  }

  // 输出处理后的JSON结果
  print(jsonEncode(jsonData));
}

代码说明

  • 先将JSON字符串解析为Dart的Map和List,方便直接修改数据
  • 把匹配列表转为Set,因为Set.contains()的查找时间复杂度为O(1),比List的O(n)效率更高
  • 直接遍历result数组中的每个对象,判断其id是否在目标集合中,存在则添加指定键值对
  • 彻底避免了原代码中因找不到id导致的索引越界问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:55:00