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);
};
相关推荐
烛阴1 小时前
Three.js 零基础入门:手把手打造交互式 3D 几何体展示系统
javascript·webgl·three.js
颜酱1 小时前
单调栈:从模板到实战
javascript·后端·算法
代码匠心2 小时前
AI 自动编程:一句话设计高颜值博客
前端·ai·ai编程·claude
_AaronWong3 小时前
Electron 实现仿豆包划词取词功能:从 AI 生成到落地踩坑记
前端·javascript·vue.js
cxxcode3 小时前
I/O 多路复用:从浏览器到 Linux 内核
前端
用户5433081441943 小时前
AI 时代,前端逆向的门槛已经低到离谱 — 以 Upwork 为例
前端
JarvanMo3 小时前
Flutter 版本的 material_ui 已经上架 pub.dev 啦!快来抢先体验吧。
前端
JohnYan3 小时前
工作笔记-CodeBuddy应用探索
javascript·ai编程·aiops
恋猫de小郭3 小时前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
哀木4 小时前
给自己整一个 claude code,解锁编程新姿势
前端