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);
};
相关推荐
toooooop82 分钟前
本地开发环境webScoket调试,保存html即用
前端·css·websocket
山有木兮木有枝_8 分钟前
手动封装移动端下拉刷新组件的设计与实现
前端
阳光阴郁大boy9 分钟前
大学信息查询平台:一个现代化的React教育项目
前端·react.js·前端框架
小菜全16 分钟前
uniapp新增页面及跳转配置方法
开发语言·前端·javascript·vue.js·前端框架
AlexMercer101219 分钟前
[前端]1.html基础
前端·笔记·学习·html
白水清风27 分钟前
关于Js和Ts中类(class)的知识
前端·javascript·面试
前端Hardy29 分钟前
只用2行CSS实现响应式布局,比媒体查询更优雅的布局方案
javascript·css·html
小菜全38 分钟前
uniapp基础组件概述
前端·css·vue.js·elementui·css3
小天呐1 小时前
qiankun 微前端接入实战
前端·js·微前端
周航宇JoeZhou1 小时前
JP4-7-MyLesson后台前端(五)
java·前端·vue·elementplus·前端项目·mylesson·管理平台