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

JavaScript中实现含频次统计的对象扁平化最优方案

JavaScript 对象转换简洁实现方案

要完成从原格式到统计姓名次数格式的转换,最简洁的方式是结合原生API组合实现:

// 原输入对象
const input = {
  0: { State: true, Name: 'bob' },
  1: { State: true, Name: 'candice' },
  2: { State: true, Name: 'allen' },
  3: { State: true, Name: 'bob' },
  4: { State: true, Name: 'bob' },
  5: { State: true, Name: 'candice' }
};

// 一步完成转换
const output = Object.fromEntries(
  Object.entries(
    Object.values(input)
      .filter(item => item.State) // 可选:过滤State为false的条目
      .reduce((acc, { Name }) => {
        acc[Name] = (acc[Name] || 0) + 1;
        return acc;
      }, {})
  ).map(([Name, Count], idx) => [idx, { Name, Count }])
);

console.log(output);

代码说明:

  1. Object.values(input):将原索引对象转为数组,便于遍历处理。
  2. filter(item => item.State):可选步骤,若原数据存在State为false的条目,可通过此步骤过滤。
  3. reduce统计次数:遍历数组,以姓名为键累加出现次数,得到{ bob: 3, candice: 2, allen: 1 }格式的统计对象。
  4. Object.entries + map:将统计对象的键值对转换为[索引, { Name, Count }]结构。
  5. Object.fromEntries:将上述数组转回索引式对象,得到最终目标格式。

若无需过滤State,直接移除filter步骤即可进一步简化代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:12:56