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

如何优化JS循环逻辑 批量拆分单对象内多任务为独立子对象

实现方案

你可以通过正则匹配提取每个属性名末尾的数字序号,按序号动态分组即可,后续新增多少个任务都不需要调整代码逻辑:

const tasks = {
    title1: "Quiet Time",
    title2: "Study",
    title3: "Go Jogging",
    title4: "Eat Breakfast",
    description1: "",
    description2: "",
    decription3: "This is going to help to reach my goals and my life to the fullest",
    decription4: "",
    date1: "05/02/2020",
    date2: "01/02/2020",
    date3: "tomorrow",
    date4: "today",
    time1: "08:12",
    time2: "13:15",
    time3: "12:36",
    time4: "13:25",
    completed1: false,
    completed2: true,
    completed3: false,
    completed4: true,
    priority1: "red",
    priority2: "yellow",
    priority3: "black",
    priority4: "white",
    tags1: ["Personal", "Work", "School"],
    tags2: ["Personal", "School", "Diary Entry"],
    tags3: ["Content Creation", "Personal"],
    tags4: ["Personal"]
}

// 用数组存储所有任务,下标对应任务序号
const taskList = []
for (let [key, value] of Object.entries(tasks)) {
    // 提取属性名末尾的数字序号
    const num = key.match(/\d+$/)?.[0]
    if (!num) continue
    // 对应序号的任务对象不存在则初始化
    if (!taskList[num]) {
        taskList[num] = {}
    }
    // 可选:去掉属性名末尾的数字后缀,让单任务对象的键更简洁,不需要可以直接用原key赋值
    const pureKey = key.replace(/\d+$/, '')
    taskList[num][pureKey] = value
}

// 最终taskList[1]对应原来的task1,taskList[2]对应原来的task2,以此类推

逻辑说明:

  • 正则/\d+$/可以匹配属性名末尾的所有数字,不管是个位数还是多位数的序号都能正常识别,后续新增task5、task10都可以自动完成分组
  • 如果你需要保留原来的属性名后缀,直接把赋值语句里的pureKey替换成key即可
  • 如果你需要和原逻辑一样单独声明任务变量,可以在分组完成后赋值即可:
    const task1 = taskList[1]
    const task2 = taskList[2]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:36:00