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

如何基于order键合并对象,将差异化字段重命名为新键存储?

基于order字段合并对象并重命名字段

需求说明

  • 以order字段为标识合并数组对象:相同order值的对象合并为一个
  • 原对象的question字段需按顺序重命名为messageType、eligibleUsers
  • 原对象的question_user字段需按顺序命名为question_user1、question_user2
  • 公共字段(如question_type、is_required)保留其一即可,choices字段取同组第一个对象的值

输入数组

[
  {
    "question": "whats name",
    "question_type": "dropdown",
    "is_required": true,
    "order": 2,
    "question_user":"employee",
    "choices": [{"id": 44,"choice": "Raj"},{"id": null,"choice": "Raj2"}]
  },
  {
    "question": "whats",
    "question_type": "dropdown",
    "is_required": true,
    "order": 2,
    "question_user":"user",
    "choices": [{"id": 1,"choice": "qw"},{"id": null,"choice": "qw2"}]
  }
]

期望输出

[
  {
    "messageType": "whats name",
    "eligibleUsers": "whats",
    "question_type": "dropdown",
    "is_required": true,
    "order": 2,
    "question_user1":"employee",
    "question_user2":"user",
    "choices": [{"id": 44,"choice": "Raj"},{"id": null,"choice": "Raj2"}]
  }
]

解决方案

以下是JavaScript/TypeScript的实现代码:

const mergeByOrder = (arr) => {
  const groups = {};
  
  arr.forEach((item, index) => {
    const { order, question, question_user, ...rest } = item;
    if (!groups[order]) {
      groups[order] = {
        ...rest,
        order
      };
    }
    // 重命名question字段
    if (index === 0) {
      groups[order].messageType = question;
    } else {
      groups[order].eligibleUsers = question;
    }
    // 重命名question_user字段
    groups[order][`question_user${index + 1}`] = question_user;
  });
  
  return Object.values(groups);
};

// 测试示例
const input = [
  {"question": "whats name","question_type": "dropdown","is_required": true,"order": 2,"question_user":"employee","choices": [{"id": 44,"choice": "Raj"},{"id": null,"choice": "Raj2"}]},
  {"question": "whats","question_type": "dropdown","is_required": true,"order": 2,"question_user":"user","choices": [{"id": 1,"choice": "qw"},{"id": null,"choice": "qw2"}]}
];

const output = mergeByOrder(input);
console.log(output);

代码说明

  1. 分组初始化:用对象groups按order值存储待合并对象,首次遇到某个order时,复制该对象的公共字段(排除question、question_user)作为合并对象的基础
  2. 字段重命名:
    • 遍历数组时,第一个对象的question赋值给messageType,第二个赋值给eligibleUsers
    • question_user字段通过遍历索引拼接序号,生成question_user1、question_user2
  3. 结果转换:将groups对象的所有值转为数组,得到最终合并后的结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:53:23