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

JavaScript中如何在sectionname变化时重置section_index序号

实现section_name变化时section_index重新从1计数的方案

原代码里的map方法没法跟踪前一个元素的sectionname状态,要实现这个需求,得借助能记录状态的方式,下面给两种实用的实现方式:

方法一:用Array.reduce()(纯函数式,无外部变量)

这种方式通过reduce累积结果数组,每次处理元素时对比当前section和结果数组最后一项的section,判断是否需要重置计数:

// 先把user.qstn转为键值对数组(和原逻辑一致)
const qstnEntries = Object.entries(user.qstn);

const qstndata = qstnEntries.reduce((resultList, [key, values], index) => {
  // 获取结果列表最后一项的section名称
  const lastSection = resultList.length ? resultList[resultList.length - 1].section_name : null;
  
  if (values.sectionname !== lastSection) {
    // 切换section,section_index从1开始
    resultList.push({
      question_id: values._id,
      qs_no: index + 1,
      in_state: 0,
      section_index: 1,
      section_name: values.sectionname
    });
  } else {
    // 同个section,计数递增
    const lastItem = resultList[resultList.length - 1];
    resultList.push({
      question_id: values._id,
      qs_no: index + 1,
      in_state: 0,
      section_index: lastItem.section_index + 1,
      section_name: values.sectionname
    });
  }
  return resultList;
}, []);

方法二:用map结合外部状态(简单直接)

在map外面定义两个变量记录当前section和计数,遍历的时候更新状态即可:

let currentSection = null;
let sectionCount = 0;

const qstndata = Object.entries(user.qstn).map(([key, values], index) => {
  if (values.sectionname !== currentSection) {
    currentSection = values.sectionname;
    sectionCount = 1;
  } else {
    sectionCount++;
  }
  
  return {
    question_id: values._id,
    qs_no: index + 1,
    in_state: 0,
    section_index: sectionCount,
    section_name: values.sectionname
  };
});

注意事项

如果user.qstn里的元素不是按sectionname连续分组的,需要先按section排序,否则同个section的section_index会被多次重置:

// 先按sectionname排序
const qstnEntries = Object.entries(user.qstn)
  .sort((a, b) => a[1].sectionname.localeCompare(b[1].sectionname));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:52:11