map优化对象数组

假设下面这个数组是你需要使用的数组,是否感觉他很笨重呢?

javascript 复制代码
const citydate3 = ref([
  {
    text: now.getFullYear() - 1,
    id: 0,
    children: [
      { text: "全年", id: 0 },
      { text: 1, id: 1 },
      { text: 2, id: 2 },
      { text: 3, id: 3 },
      { text: 4, id: 4 },
      { text: 5, id: 5 },
    ],
  },
  {
    text: now.getFullYear(),
    id: 1,
    children: [
      { text: "全年", id: 0 },
      { text: 1, id: 1 },
      { text: 2, id: 2 },
      { text: 3, id: 3 },
      { text: 4, id: 4 },
      { text: 5, id: 5 },
    ],
  },
  {
    text: now.getFullYear() + 1,
    id: 3,
    children: [
      { text: "全年", id: 0 },
      { text: 1, id: 1 },
      { text: 2, id: 2 },
      { text: 3, id: 3 },
      { text: 4, id: 4 },
      { text: 5, id: 5 },
    ],
  },
]);

这是一个日期picker组件的数据,外层text代表年份,内层text代表那一年的月份,id均为index,下面运用map方法进行改写

javascript 复制代码
const citydate3 = ref(
  [now.getFullYear() - 1, now.getFullYear(), now.getFullYear() + 1].map((text, index) => ({
    text,
    id: index,
    children: ["全年", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((text, index) => ({
      text,
      id: index,
    })),
  })),
);

其实map解析数组和for循环有点像,数组解析出来的每一项作为text,index为每一项的索引
现已知外层索引为1,内层索引为12,你可以使用以下方法访问外层和内层的text

javascript 复制代码
const pickok = () => {
  //获取外层对象
  const obj1 = citydate3.value.find((obj) => obj.id === 1);
  //获取内层对象
  const obj2 = obj1.children.find((obj) => obj.id === 6);
  console.log(obj1.text, obj2.text);
};
相关推荐
进击的尘埃35 分钟前
拖拽搭建场景下的智能布局算法:栅格吸附、参考线与响应式出码
javascript
小猪努力学前端40 分钟前
基于PixiJS的试玩广告开发-续篇
前端·javascript·游戏
bluceli1 小时前
前端构建工具深度解析:从Webpack到Vite的演进之路
前端
wuhen_n1 小时前
v-model 的进阶用法:搞定复杂的父子组件数据通信
前端·javascript·vue.js
wuhen_n1 小时前
TypeScript 深度加持:让你的组合式函数拥有“钢筋铁骨”
前端·javascript·vue.js
滕青山1 小时前
基于 ZXing 的 Vue 在线二维码扫描器实现
前端·javascript·vue.js
Kayshen1 小时前
我在设计工具里实现了一个 Agent Team:多智能体协作生成 UI 的实战经验
前端·aigc·agent
swipe2 小时前
深入理解 JavaScript 中的 this 绑定机制:从原理到实战
前端·javascript·面试
Json_Lee2 小时前
2026 年了,多 Agent 编码该怎么选?agent-team vs Claude Agent Teams vs Claude Squad vs Met
前端·后端·vibecoding
Novlan12 小时前
Stepper 小数输入精度丢失 Bug 修复
前端