地图列表 - 将相同的值与单个元素合并 [duplicate]

List of map - merge same value with single element [duplicate]

提问人:iPatel 提问时间:10/30/2023 更新时间:10/30/2023 访问量:91

问:

我有如下列表

[
  {
    "id": "1",
    "name": "Aaa",
    "title": "Aaa like your photo"
  },
  {
    "id": "2",
    "name": "Bbb",
    "title": "Bbb like your video"
  },
  {
    "id": "1",
    "name": "Ccc",
    "title": "Ccc like your photo"
  },
  {
    "id": "1",
    "name": "Ddd",
    "title": "Ddd like your photo"
  }
]

我想与相同的合并,结果将是mapid

[
  {
    "id": "1",
    "name": "Aaa, Ccc and Ddd",
    "title": "Aaa, Ccc and Ddd like your photo"
  },
  {
    "id": "2",
    "name": "Bbb",
    "title": "Bbb like your video"
  }
]

我知道 nester loop,但正在寻找任何捷径。forEach

JavaScript的 扑动 列表 飞镖

评论

0赞 pskink 10/30/2023
使用 groupListsBy

答:

0赞 WebDesk Solution 10/30/2023 #1

请查看下面提供的代码。我相信这可能是有益的。

void main() {
  String jsonString = '''
    [
  {
    "id": "1",
    "name": "Aaa",
    "title": "Aaa like your photo"
  },
  {
    "id": "2",
    "name": "Bbb",
    "title": "Bbb like your video"
  },
  {
    "id": "1",
    "name": "Ccc",
    "title": "Ccc like your photo"
  },
  {
    "id": "1",
    "name": "Ddd",
    "title": "Ddd like your photo"
  }
]
  ''';

  var data = List<Map<String, String>>.from(jsonDecode(jsonString));

  var result = <String, Map<String, String>>{};

  data.forEach((element) {
    var id = element['id'];
    result[id] = {
      'id': id!,
      'name': '${result[id]?['name'] ?? ''}, ${element['name']!}',
      'title': '${result[id]?['title'] ?? ''}, ${element['title']!}'
    };
  });

  print(result.values.toList());
}
1赞 tuckermassad 10/30/2023 #2

我建议实现如下所示的内容,其中创建一个新对象,该对象具有 object.name 值列表的键和值。使用您给出的以下示例列表输入,如果您执行了类似以下操作id

function mergeObjectsWithSameId(inputArray) {
    return inputArray.reduce((acc, curr) => {
      if (!acc[curr.id]) {
        acc[curr.id] = [];
      }
      acc[curr.id].push(curr.name);
      return acc;
    }, {});
  }

将为您提供以下输出:

{
  "1": ["Aaa", "Ccc" "Ddd"],
  "2": ["Bbb"]
  ]
}

您也可以删除列表中的部分,然后使用给定键中的每个键来显示喜欢照片的部分,例如:titlenamename

const names = mergeObjectsWithSameId(input);
// If we want to display all names that "liked" a photo with id of "1"
const stringToDisplay = `${names.join(', ')} liked your photo`; // "Aaa, Ccc, Ddd liked your photo"