如何使用JavaScript按指定键对对象数组进行分组?
按属性分组数组的JavaScript实现
你可以通过Array.reduce()先将数组按type属性分组为对象,再用Object.entries()和Array.map()转换为期望的数组格式,全程无需额外库:
完整代码
const input = [ { "type": "typeA", "label": "labelA", "placeholders": ["b", "a", "r"] },{ "type": "typeB", "label": "labelB", "placeholders": ["x", "y", "z"] },{ "type": "typeA", "label": "labelAAA", "placeholders": ["a", "b", "c"] } ]; // 步骤1:用reduce按type分组 const groupedObj = input.reduce((acc, current) => { // 提取type,剩余属性作为item内容 const { type, ...itemContent } = current; // 如果当前type还没在分组对象里,初始化空数组 if (!acc[type]) { acc[type] = []; } // 将当前item的内容推入对应type的数组 acc[type].push(itemContent); return acc; }, {}); // 步骤2:将分组对象转换为期望的数组格式 const output = Object.entries(groupedObj).map(([type, items]) => ({ type, items })); console.log(output);
代码说明
reduce分组:遍历原数组,以type为键构建分组对象,每个键对应的值是该类型下的所有label和placeholders集合。- 转换为目标数组:通过
Object.entries()将分组对象的键值对转为数组,再用map()把每个键值对映射为包含type和items的对象。
注意
你提供的期望输出中,typeB的placeholders与输入不符(输入是["x","y","z"],期望输出写了["b","a","r"]),上述代码会保留输入中的原始数据,生成正确的分组结果。
内容的提问来源于stack exchange,提问作者Stéphane GRILLON
相关产品推荐
相关产品推荐

