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

如何使用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);

代码说明

  1. reduce分组:遍历原数组,以type为键构建分组对象,每个键对应的值是该类型下的所有label和placeholders集合。
  2. 转换为目标数组:通过Object.entries()将分组对象的键值对转为数组,再用map()把每个键值对映射为包含type和items的对象。

注意

你提供的期望输出中,typeB的placeholders与输入不符(输入是["x","y","z"],期望输出写了["b","a","r"]),上述代码会保留输入中的原始数据,生成正确的分组结果。

内容的提问来源于stack exchange,提问作者Stéphane GRILLON

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:40:17