JS按对象数组month字段分组后如何分组渲染月份标题与内容
实现方案
你已经拿到按month分组的对象后,核心是通过Object.entries()取出对象中所有「月份值-对应月份条目数组」的键值对,做双层遍历即可完成渲染:第一层遍历每个月份,先渲染月份标题;第二层遍历当前月份下的所有条目,渲染对应的desc内容。
注意:JS普通对象的键遍历顺序在部分旧环境下不保证和插入顺序一致,如果需要严格按月份从小到大展示,要先对键值对做排序处理。
原生JS(直接操作DOM)完整示例
// 这里替换成你通过reduce得到的分组结果 const groupedData = { 2: [{id: '0001',month:2,desc:'objectone'}], 4: [ {id: '0001',month:4,desc:'objecttwo'}, {id: '0001',month:4,desc:'objectthree'}, {id: '0001',month:4,desc:'objectfour'} ], 5: [ {id: '0001',month:5,desc:'objectfive'}, {id: '0001',month:5,desc:'objectsix'} ] } // 替换成你页面中实际用来挂载内容的容器选择器 const container = document.getElementById('content-container') Object.entries(groupedData) // 按月份升序排序,不需要排序可以删掉这行 .sort(([monthA], [monthB]) => Number(monthA) - Number(monthB)) .forEach(([month, itemList]) => { // 渲染月份标题 const monthTitle = document.createElement('h1') monthTitle.textContent = `Month ${month}` container.appendChild(monthTitle) // 渲染当前月份下所有条目的desc itemList.forEach(item => { const descEl = document.createElement('p') descEl.textContent = item.desc container.appendChild(descEl) }) })
常见前端框架写法参考
React 写法
export default function MonthList({ groupedData }) { return ( <div className="list-container"> {Object.entries(groupedData) .sort(([monthA], [monthB]) => Number(monthA) - Number(monthB)) .map(([month, itemList]) => ( <section key={month}> <h1>Month {month}</h1> {itemList.map((item, index) => ( <p key={`${item.id}-${index}`}>{item.desc}</p> ))} </section> ))} </div> ) }
Vue3 写法
<template> <div class="list-container"> <section v-for="(itemList, month) in sortedData" :key="month"> <h1>Month {{ month }}</h1> <p v-for="(item, idx) in itemList" :key="`${item.id}-${idx}`"> {{ item.desc }} </p> </section> </div> </template> <script setup> import { computed } from 'vue' const props = defineProps({ groupedData: { type: Object, required: true } }) const sortedData = computed(() => { return Object.fromEntries( Object.entries(props.groupedData) .sort(([monthA], [monthB]) => Number(monthA) - Number(monthB)) ) }) </script>
内容的提问来源于stack exchange,提问作者fedjedmedjed
相关产品推荐
相关产品推荐

