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);
};
相关推荐
快递鸟2 分钟前
物流信息总滞后?快递鸟在途监控 API,毫秒级响应让物流透明不等待
前端
小蹦跶儿11 分钟前
解决Webpack 打包报错:TypeError: Cannot assign to read only property 'exports' ?
javascript·vue.js·webpack
fruge16 分钟前
前端注释规范:如何写“后人能看懂”的注释(附示例)
前端
老华带你飞17 分钟前
医疗保健|医疗养老|基于Java+vue的医疗保健系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·医疗保健
小飞大王66625 分钟前
JavaScript基础知识总结(四):常见内置构造函数,正则表达式,作用域与闭包
前端·javascript·正则表达式
3秒一个大27 分钟前
Ajax 数据请求详解:从概念到实战
javascript
清凉夏日44 分钟前
Flutter 国际化完整指南
前端·flutter
Jony_1 小时前
动态代理机制
前端
掘金一周1 小时前
重新思考 weapp-tailwindcss 的未来 | 掘金一周 11.13
前端·人工智能·后端
Pu_Nine_91 小时前
Vue 3 项目 ESLint 配置详解:初始模板的正确配置
前端·javascript·vue.js