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

如何按相同parent_id组织JSON数据并实现分类标题+子项按钮展示?

按parent_id组织分类与子项的最优方案

一、数据组织方式

1. 前端实时结构化(中小数据量首选)

直接在前端遍历原始数组,通过映射表快速匹配父分类,把扁平数据转成分层结构,时间复杂度O(n),效率拉满。

代码示例(JavaScript):

const rawData = { /* 你的原始JSON数据 */ };

const categoryMap = {};
const structuredCategories = [];

rawData.data.categories.forEach(item => {
  if (item.parent_id === 0) {
    // 父分类初始化,添加children数组
    categoryMap[item.id] = { ...item, children: [] };
    structuredCategories.push(categoryMap[item.id]);
  } else {
    // 子项匹配到对应父分类
    categoryMap[item.parent_id]?.children.push(item);
  }
});

// structuredCategories就是最终的分层数据

2. 后端提前结构化(大数据量/多端复用首选)

如果数据量较大,或者多个前端需要复用结构,让后端直接返回分层数据,前端无需额外处理,减少前端计算开销。示例结构:

{
  "data": {
    "structured_categories": [
      {
        "id": 62,
        "parent_id": 0,
        "category_name": "Category 1",
        "category_slug": "category1",
        "children": [{"id":10, "parent_id":62, ...}]
      },
      // 其他分类...
    ]
  }
}

二、展示实现方案

原生HTML+JS实现

HTML结构

<div class="category-container"></div>

样式优化(可选)

.category-section {
  margin: 20px 0;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}
.category-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
.category-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.category-button {
  padding: 6px 12px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}
.category-button:hover {
  background: #e0e0e0;
}

渲染逻辑

const container = document.querySelector('.category-container');

structuredCategories.forEach(category => {
  // 创建分类区块
  const section = document.createElement('div');
  section.className = 'category-section';

  // 添加分类标题
  const title = document.createElement('h3');
  title.className = 'category-title';
  title.textContent = category.category_name;
  section.appendChild(title);

  // 创建按钮容器
  const btnContainer = document.createElement('div');
  btnContainer.className = 'category-buttons';

  // 生成子项按钮
  category.children.forEach(item => {
    const btn = document.createElement('button');
    btn.className = 'category-button';
    btn.textContent = item.category_name;
    // 绑定点击事件(示例:打印slug,实际可替换为跳转逻辑)
    btn.addEventListener('click', () => console.log(`跳转至:${item.category_slug}`));
    btnContainer.appendChild(btn);
  });

  section.appendChild(btnContainer);
  container.appendChild(section);
});

Vue 3简化实现

<template>
  <div class="category-container">
    <div class="category-section" v-for="cate in structuredCategories" :key="cate.id">
      <h3 class="category-title">{{ cate.category_name }}</h3>
      <div class="category-buttons">
        <button 
          class="category-button" 
          v-for="item in cate.children" 
          :key="item.id"
          @click="handleClick(item)"
        >
          {{ item.category_name }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const structuredCategories = ref([]);

onMounted(() => {
  // 这里获取并结构化数据,赋值给structuredCategories.value
});

const handleClick = (item) => {
  // 处理按钮点击逻辑,比如跳转
  console.log(`点击了${item.category_name},slug:${item.category_slug}`);
};
</script>

<style scoped>
/* 复用前面的CSS样式 */
</style>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:18:23