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

如何按userID聚合后端对象数组,生成全量属性的自定义用户对象

合并同userID的分散用户属性对象

问题背景

从后端获取的用户数据分散在多个对象中,同一userID的不同属性(地址、电话、邮箱等)分别存放在不同对象里,需要将同一userID的所有属性合并到单个对象中。

原始数据

[{"userID":1,"firstName":"George","lastName":"Russell","addressID":"1","address_value":"27 London Street E146AA","expDate":"2022-12-12T17:09:37.000Z"},{"userID":1,"firstName":"George","lastName":"Russell","phoneId":"1","phone_value":"97627445368"},{"userID":2,"firstName":"George","lastName":"Russell","phoneId":"2","phone_value":"07884076692"},{"userID":1,"firstName":"George","lastName":"Russell","emailId":"1","email_value":"georgerussell@outlook.com"},{"userID":1,"firstName":"George","lastName":"Russell","employerId":"1","employer_value":"QMUL"},{"userID":28,"firstName":"Binny","lastName":"Bansal","employerId":"2","employer_value":"Google Inc"},{"userID":1,"firstName":"George","lastName":"Russell","nationalityId":"1","nationality":"Indian"},{"userID":1,"firstName":"George","lastName":"Russell","passportId":"1","passportNumber":"123445567"}]

目标格式

希望将同一userID的属性合并,示例如下:

{
  addressID: "1",
  address_value: "27 London Street E146AA",
  expDate: "2022-12-12T17:09:37.000Z",
  firstName: "George",
  lastName: "Russell",
  userID: 1,
  phoneId: "1",
  phone_value: "97627445368",
  emailId:"1",
  email_value:"georgerussell@outlook.com",
  employerId:"1",
  employer_value:"QMUL",
  nationalityId:"1",
  nationality:"Indian",
  passportId:"1",
  passportNumber:"123445567"
}

原代码问题分析

你写的代码存在两个核心问题:

  1. 用数组存储同一userID的对象,而非直接合并属性:r[a.userID] = r[a.userID] || [] 这行把每个用户的对象都放进了数组,没有执行属性合并逻辑。
  2. 后续遍历仅打印对象,未实现合并:注释掉的finalResult.push(...el1)逻辑错误,...el1会把对象的键名作为数组元素推入,完全不符合合并需求。

原代码:

result = data.reduce(function (r, a) {
        r[a.userID] = r[a.userID] || [];
        r[a.userID].push(a);
        return r;
    }, Object.create(null));
console.log(result);
const finalResult = [];
Object.keys(result).forEach(el => {
  result[el].forEach(el1 => {
    console.log(el1)
    //finalResult.push(...el1)
  })
})

正确解决方案

使用reduce直接合并同一userID的属性,每次迭代用Object.assign或扩展运算符把当前对象的属性合并到用户对应的对象上:

const mergedData = data.reduce((acc, current) => {
  const userId = current.userID;
  // 若累加器中已有该用户对象,合并属性;否则初始化新对象
  acc[userId] = acc[userId] ? { ...acc[userId], ...current } : { ...current };
  return acc;
}, {});

// 转换为数组格式(按需使用)
const finalResult = Object.values(mergedData);
console.log(finalResult);

代码说明

  • reduce的累加器acc以userID为键,存储每个用户的合并后对象。
  • 每次迭代时,判断累加器中是否已有该用户的对象:若有则用扩展运算符合并属性;若没有则直接创建当前对象的副本。
  • 最后用Object.values将对象转为数组,得到符合需求的合并后数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:27:28