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

基于Interface属性值创建新对象数组的ES5实现咨询

ES5 实现按对象Interface属性值分组生成指定结构数组

功能说明

可实现将原始对象数组中,Interface属性值为GE5、GE6的对象分别归类分组,最终返回包含2个分组对象的新数组,全量采用ES5语法实现,兼容低版本浏览器运行环境。

实现代码

// 示例原始对象数组,可替换为你的实际数据
var originData = [
  { id: 1, Interface: "GE5", value: "a" },
  { id: 2, Interface: "GE6", value: "b" },
  { id: 3, Interface: "GE5", value: "c" },
  { id: 4, Interface: "GE6", value: "d" },
  { id: 5, Interface: "GE5", value: "e" }
];

// 分组核心方法
function groupByInterface(arr) {
  var groupTemp = {};
  var result = [];
  var i, current, interfaceKey;

  // 若要求无对应数据时也保留两个空分组,可取消注释下方3行代码
  // groupTemp["GE5"] = { groupName: "GE5", list: [] };
  // groupTemp["GE6"] = { groupName: "GE6", list: [] };
  // result.push(groupTemp["GE5"], groupTemp["GE6"]);

  for (i = 0; i < arr.length; i++) {
    current = arr[i];
    interfaceKey = current.Interface;
    // 仅保留GE5、GE6两个分组,可根据实际需求修改匹配规则
    if (interfaceKey !== "GE5" && interfaceKey !== "GE6") {
      continue;
    }
    // 初始化不存在的分组(如果已提前初始化分组可删除下方if判断)
    if (!groupTemp[interfaceKey]) {
      groupTemp[interfaceKey] = {
        groupName: interfaceKey,
        list: []
      };
      result.push(groupTemp[interfaceKey]);
    }
    // 向对应分组添加当前对象
    groupTemp[interfaceKey].list.push(current);
  }
  return result;
}

// 调用方法获取结果
var groupedResult = groupByInterface(originData);

输出结构说明

运行后得到的groupedResult结构如下:

[
  {
    groupName: "GE5",
    list: [
      { id: 1, Interface: "GE5", value: "a" },
      { id: 3, Interface: "GE5", value: "c" },
      { id: 5, Interface: "GE5", value: "e" }
    ]
  },
  {
    groupName: "GE6",
    list: [
      { id: 2, Interface: "GE6", value: "b" },
      { id: 4, Interface: "GE6", value: "d" }
    ]
  }
]

如果需要调整分组对象的属性名,直接修改groupTemp[interfaceKey]初始化时的字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:54:01