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

如何用JavaScript处理嵌套对象数组 按属性分组统计值出现次数

解决思路
  • 第一步:扁平化原始嵌套数组,提取所有包含trait_type和value的属性对象,消除外层数组的嵌套层级
  • 第二步:构建中间统计映射表,以trait_type为一级键,对应属性下的value为二级键,累计相同值的出现次数
  • 第三步:将中间统计映射表转换为目标格式,每个trait_type单独作为一个对象的键,对应的值转换为{值: 计数}格式的对象数组
完整实现代码
const rawData = [
    [
        { trait_type: 'Type:', value: 'Epic' },
        { trait_type: 'Clan:', value: 'Vampire' },
    ],
    [{ trait_type: 'Rare Accessory:', value: 'Rainbow Glass' }],
    [{ trait_type: 'Rarity:', value: 'Common' }],
    [{ trait_type: 'Type:', value: 'Common' }],
    [{ trait_type: 'Type:', value: 'Rare' }],
    [{ trait_type: 'Type:', value: 'Epic' }, { trait_type: 'Rarity:', value: 'Common' }],
];

// 1. 扁平化嵌套数组,提取所有属性对象
const flatItems = rawData.flat();

// 2. 构建统计映射表
const statMap = {};
flatItems.forEach(item => {
    const { trait_type, value } = item;
    // 初始化对应属性类型的统计容器
    if (!statMap[trait_type]) {
        statMap[trait_type] = {};
    }
    // 累加属性值的出现次数
    statMap[trait_type][value] = (statMap[trait_type][value] || 0) + 1;
});

// 3. 转换为目标输出结构
const result = Object.entries(statMap).map(([traitType, valueCount]) => {
    return {
        [traitType]: Object.entries(valueCount).map(([val, count]) => ({ [val]: count }))
    };
});

// 打印结果验证
console.log(JSON.stringify(result, null, 2));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:54:03