如何将JSON文件中的对象按共同的x、y字段值进行分组
按x、y字段分组JSON对象实现方案
核心思路
- 将每个对象的
x和y字段值组合为唯一分组标识,普通场景可直接用特殊分隔符拼接(如_、|等) - 借助临时映射表存储所有分组,遍历原始数据时将同组对象归集到对应数组中
- 最终提取映射表的所有值,即可得到符合要求的二维数组结果
JavaScript实现
注:你提供的示例代码中对象属性赋值误用了=,标准JS对象/JSON应使用:,修正后实现如下:
const data = [ {"x": "0", "y": "0", "k": "0"}, {"x": "0", "y": "0", "k": "1"}, {"x": "1", "y": "2", "k": "0"}, {"x": "1", "y": "2", "k": "5"}, {"x": "2", "y": "2", "k": "10"}, {"x": "1", "y": "2", "k": "12"} ] const groupMap = {} data.forEach(item => { // 构造唯一分组key,若x/y值可能包含下划线可更换为其他罕见分隔符 const groupKey = `${item.x}_${item.y}` if (!groupMap[groupKey]) groupMap[groupKey] = [] groupMap[groupKey].push(item) }) const result = Object.values(groupMap)
Python实现
data = [ {"x": "0", "y": "0", "k": "0"}, {"x": "0", "y": "0", "k": "1"}, {"x": "1", "y": "2", "k": "0"}, {"x": "1", "y": "2", "k": "5"}, {"x": "2", "y": "2", "k": "10"}, {"x": "1", "y": "2", "k": "12"} ] group_map = {} for item in data: group_key = f"{item['x']}_{item['y']}" if group_key not in group_map: group_map[group_key] = [] group_map[group_key].append(item) result = list(group_map.values())
上述两种语言的实现输出结果均与你给出的期望结构完全一致。
内容的提问来源于stack exchange,提问作者Axxb 2020
相关产品推荐
相关产品推荐

