如何在Vue中使用.reduce对对象/数组进行分组并遍历?
动态按ID分组数组并展示的解决方案
问题场景
你有一个包含未知ID的对象数组,需要按ID对对象进行分组,且无法提前预知会生成多少个分组。不想用静态的分组数组循环写法,希望实现动态遍历展示的效果。
示例数组:
const originalArray = [ { id: 11, item: "item" }, { id: 49, item: "item" }, { id: 11, item: "item" }, { id: 20, item: "item" }, { id: 49, item: "item" }, { id: 83, item: "item" }, ];
解决方案
不要动态命名array-0、array-1这类变量,这会大幅增加后续遍历的复杂度。推荐用对象或Map存储分组结果:用ID作为key,对应ID的对象数组作为value,之后直接遍历这个结构即可。
1. 按ID分组
用Array.reduce()快速实现分组:
// 用对象分组(适合ID为字符串/数字的场景) const groupedById = originalArray.reduce((acc, current) => { // 若当前ID未在累加器中,初始化空数组 if (!acc[current.id]) { acc[current.id] = []; } // 将当前对象推入对应ID的数组 acc[current.id].push(current); return acc; }, {}); // 用Map分组(适合非字符串/数字类型的ID) const groupedMap = originalArray.reduce((map, current) => { if (!map.has(current.id)) { map.set(current.id, []); } map.get(current.id).push(current); return map; }, new Map());
2. 动态遍历展示
拿到分组结果后,直接遍历所有分组即可,无需关心分组数量:
示例1:控制台输出所有分组
// 遍历对象分组 Object.entries(groupedById).forEach(([id, items]) => { console.log(`ID为${id}的分组:`); items.forEach(item => console.log(item)); }); // 遍历Map分组 groupedMap.forEach((items, id) => { console.log(`ID为${id}的分组:`); items.forEach(item => console.log(item)); });
示例2:前端DOM动态渲染
如果是前端场景,可动态生成DOM元素展示:
const container = document.getElementById('group-container'); Object.entries(groupedById).forEach(([id, items]) => { // 创建分组标题 const groupTitle = document.createElement('h3'); groupTitle.textContent = `ID: ${id}`; container.appendChild(groupTitle); // 创建分组列表 const list = document.createElement('ul'); items.forEach(item => { const listItem = document.createElement('li'); listItem.textContent = item.item; list.appendChild(listItem); }); container.appendChild(list); });
这样不管有多少个不同的ID,都能自动完成分组和展示,完全不需要静态指定分组数量或数组名称。
内容的提问来源于stack exchange,提问作者Philippe
相关产品推荐
相关产品推荐

