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 分钟前
前端必看 | 零基础入门 | 你真的懂CSS选择器吗?
前端·css·html
程序猿大波10 分钟前
基于Java,SpringBoot,Vue,HTML家政服务预约系统设计
java·vue.js·spring boot
BillKu10 分钟前
vue3中,element-plus中el-input的v-model和value的用法示例
javascript·vue.js·elementui
在掘金14 分钟前
【kk-utils】Excel工具——实践篇(一)
前端·excel
香蕉可乐荷包蛋19 分钟前
vue+electron IPC+sql相关开发(一)
前端·vue.js·electron
小韩本韩!20 分钟前
electron+vue项目 设置全屏
javascript·vue.js·electron
尘寰ya23 分钟前
什么是原型污染?如何防止原型污染?
前端·面试·原型模式
鸿蒙场景化示例代码技术工程师26 分钟前
实现实时语音转文字功能鸿蒙示例代码
前端
ohMyGod_12331 分钟前
高阶函数/柯里化/纯函数
前端·react.js·前端框架
CsharpDev-奶豆哥35 分钟前
如何理解前端开发中的“换皮“
前端·css·css3