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);
};
相关推荐
Rabi'1 分钟前
编译ATK源码
前端·webpack·node.js
SoaringHeart21 分钟前
Flutter组件封装:视频播放组件全局封装
前端·flutter
TAEHENGV22 分钟前
进度跟踪模块 Cordova 与 OpenHarmony 混合开发实战
android·javascript·数据库
2501_9462243141 分钟前
旅行记录应用外观设置 - Cordova & OpenHarmony 混合开发实战
javascript·harmonyos·harvester
离&染2 小时前
vue.js2.x + elementui2.15.6实现el-select滚动条加载数据
前端·javascript·vue.js·el-select滚动加载
inferno2 小时前
HTML基础(第一部分)
前端·html
kirinlau2 小时前
pinia状态管理在vue3项目中的用法详解
前端·javascript·vue.js
zhuà!2 小时前
腾讯地图TMap标记反显,新增标记
前端·javascript·vue.js
未知原色2 小时前
web worker使用总结(包含多个worker)
前端·javascript·react.js·架构·node.js