原生JavaScript如何按user_id分组合并多个对象数组
实现方案
按user_id分组聚合的逻辑可以通过原生JS的对象存储+数组遍历实现,不需要额外依赖。
核心逻辑
- 用普通对象作为分组容器,键为
user_id,值为对应用户下的pets/house/device三类数据集合 - 遍历三个源数组时,先判断当前
user_id是否已在容器中,不存在则初始化三类空数组 - 遍历过程中做字段映射:把原数组中对应的业务字段(
animals/Habitation/xHabitation/device)统一转为x字段,保留原有的y字段,推入对应分类的数组中
完整代码
// 三个原始输入数组 const animalList = [ { animals: 'dog', user_id: 12, y: 1 }, { animals: 'cat', user_id: 1, y: 3 } ]; const habitationList = [ { Habitation: 'Appartement', user_id: 1, y: 1 }, { Habitation: 'Mansion', user_id: 12, y: 1 }, { xHabitation: 'House', user_id: 1, y: 2 } ]; const deviceList = [ { device : 'computer', user_id: 1, y: 1 }, { device : 'laptop', user_id: 1, y: 2 }, { device : 'tablet', user_id: 12, y: 1 } ]; const userGroup = {}; // 处理宠物类数据 animalList.forEach(item => { const uid = item.user_id; if (!userGroup[uid]) userGroup[uid] = { pets: [], house: [], device: [] }; userGroup[uid].pets.push({ x: item.animals, y: item.y }); }); // 处理居住类数据,兼容Habitation、xHabitation两种字段名 habitationList.forEach(item => { const uid = item.user_id; if (!userGroup[uid]) userGroup[uid] = { pets: [], house: [], device: [] }; const xVal = item.Habitation ?? item.xHabitation; userGroup[uid].house.push({ x: xVal, y: item.y }); }); // 处理设备类数据 deviceList.forEach(item => { const uid = item.user_id; if (!userGroup[uid]) userGroup[uid] = { pets: [], house: [], device: [] }; userGroup[uid].device.push({ x: item.device, y: item.y }); });
输出结果
执行后userGroup的结构完全匹配需求,注意示例中写的[1 = {...}, 12 = {...}]不是合法的JavaScript数组结构,使用对象以user_id为键存储才是符合JS语法的正确形式,访问时直接通过userGroup[目标user_id]即可拿到对应数据:
{ 1: { pets: [{ x: 'cat', y: 3 }], house: [{ x: 'Appartement', y: 1 }, { x: 'House', y: 2 }], device: [{ x: 'computer', y: 1 }, { x: 'laptop', y: 2 }] }, 12: { pets: [{ x: 'dog', y: 1 }], house: [{ x: 'Mansion', y: 1 }], device: [{ x: 'tablet', y: 1 }] } }
内容的提问来源于stack exchange,提问作者taranticoscr
相关产品推荐
相关产品推荐

