两个数组之间组合新的数组

首先要找到可以判断的条件
得要把一个数组转成对象这样就不用写那么多的循环优化代码
例如
 per: [
      { id: 3, user_id: 2, path: "/category", path_name: "分类页面" },
      { id: 4, user_id: 2, path: "/good", path_name: "商品页面" },
      { id: 6, user_id: 2, path: "/order", path_name: "订单页面" },
    ],

 menuArr: [
        {
          icon: "el-icon-location",
          title: "商品管理",
          subs: [
            { title: "商品列表", index: "/good" },
            { title: "商品分类", index: "/category" },
            { title: "品牌管理", index: "/brand" },
            { title: "商品属性管理", index: "/attribute" },
          ],
        },
        {
          icon: "el-icon-location",
          title: "订单中心",
          subs: [{ title: "订单列表", index: "/order" }],
        },
        {
          icon: "el-icon-location",
          title: "店铺运营",
          subs: [
            { title: "专题管理", index: "/topic" },
            { title: "运营数据", index: "/statdata" },
          ],
        },
      ],
// 新的数组用于存储筛选出来的数据
    let newMenu = [];
    //  获取vuex的数据
    let per = this.$store.state.per;
    // console.log(per);
    // 把vuex的数组转成对象
    let perObj = per.reduce((pre, current) => {
      pre[current.path] = current;
      return pre;
    }, {});
    // console.log(perObj);
    // 循环逐渐的数组进行两个数组之间的合并
    let menuArr = this.menuArr;
    for (var i = 0; i < menuArr.length; i++) {
      // 定义一个数组用于装subs筛选出来的对象,每循环结束一个都清空
      let arr = [];
      for (var j = 0; j < menuArr[i].subs.length; j++) {
        // console.log(path);
        let subsItem = menuArr[i].subs[j];
        let path = subsItem.index;
        // 判断path的值有没有跟perObj里的一样
        if (perObj[path]) {
          arr.push(subsItem);
        }
      }
      // console.log(arr);
      if (arr.length !== 0) {
        newMenu.push({
            // ...menuArr[i]es6的结构 就是相当于 
            // icon:menuArr[i].icon
            // icon:menuArr[i].title
            // 把新的值覆盖旧的值
          ...menuArr[i],
          subs: arr,
        });
      }
      // console.log(newMenu);
    }
    this.menuArr=newMenu;
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值