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

Vue.js中如何按分类名称属性对JSON数组数据进行分组重组

实现方案

你可以直接使用JavaScript原生的Array.reduce()方法完成分组,该方法在Vue2/Vue3环境下都可直接使用,不需要引入额外第三方库。

核心实现代码

// 你的原始JSON数据
const rawProducts = [
  {
    "id":317,
    "name":"Ingram's Camphor Cream",
    "slug":null,
    "product_category_id":15,
    "industry_id":2,
    "deleted_at":null,
    "category":{
      "id":15,
      "name":"Skincare",
      "slug":null,
      "industry_id":2,
      "deleted_at":null,
      "sku_id":3,
      "is_active":1
    }
  },
  {
    "id":323,
    "name":"Zimgold",
    "slug":null,
    "product_category_id":2,
    "industry_id":2,
    "deleted_at":null,
    "category":{
      "id":2,
      "name":"Cooking Oils",
      "slug":null,
      "industry_id":2,
      "sku_id":2,
      "is_active":1
    }
  }
]

// 按分类名称分组逻辑
const groupedProducts = rawProducts.reduce((acc, cur) => {
  // 取分类名称作为分组Key
  const categoryKey = cur.category.name
  // 不存在对应分组则先初始化空数组
  if (!acc[categoryKey]) acc[categoryKey] = []
  // 将当前产品项加入对应分组,可自行裁剪需要保留的字段
  acc[categoryKey].push(cur)
  return acc
}, {})

执行完成后groupedProducts就是你需要的目标结构。

Vue环境下的响应式用法

Vue3 组合式API

import { ref, computed } from 'vue'

// 原始产品列表(通常从接口获取赋值)
const rawProducts = ref([])
// 计算属性自动响应原始数据变化,返回分组结果
const groupedProducts = computed(() => {
  return rawProducts.value.reduce((acc, cur) => {
    const categoryKey = cur.category.name
    if (!acc[categoryKey]) acc[categoryKey] = []
    acc[categoryKey].push(cur)
    return acc
  }, {})
})

Vue2 选项式API

export default {
  data() {
    return {
      rawProducts: []
    }
  },
  computed: {
    groupedProducts() {
      return this.rawProducts.reduce((acc, cur) => {
        const categoryKey = cur.category.name
        if (!acc[categoryKey]) acc[categoryKey] = []
        acc[categoryKey].push(cur)
        return acc
      }, {})
    }
  }
}

可选优化项

  • 如果你不需要保留产品的完整原始字段,push时可自行构造需要的对象,例如acc[categoryKey].push({id: cur.id, name: cur.name})即可只保留产品ID和名称
  • 如果需要过滤已删除的数据,可在遍历开头加判断:if (cur.deleted_at || cur.category.deleted_at) return acc,跳过无效数据
  • 如果分类名称可能重复,可改用分类ID作为Key,同时额外存储分类名称即可

内容的提问来源于stack exchange,提问作者Brian Highforce Thomas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:06:03