ES6内使用map和set的记录

46 阅读1分钟

后端返回的数组总是遍历寻找数据写起来太繁琐,利用ES6的map对象可实现快速操作

 let map = new Map()
    let arr = [
      {
      name:'测试1',
      item:"ppp",
      value:"2"
    }, {
      name:'测试1',
      item:"ppp",
      value:"12"
    }, {
      name:'测试2',
      item:"ppp",
      value:"2"
    },
  ]
  arr.forEach((x) => {
     map.set(x.name,x)
  })                                                                                                                                                                                                                                                      
  console.log(map.get('测试1'))
    //拿到对应对象
    //   {
    //   name:'测试1',
    //   item:"ppp",
    //   value:"2"
    // }
    //如果数组是空则返回underfind
   console.log(map.size,"测试1"); 
   //拿到长度2 如果数组是空的则返回0
//初始化先声明 map对象
mounted() {
 this.dataMap = new Map()
}

//方法一读取数据写入map利用set不会重复的特性
xxx() {
      this.$api.xxxx().then(res => {
        this.yyy = res.result.
        res.forEach(item => {
          if (item.id) {
          //利用set插入数据 set不会插入重复的数据
          //用set插入同id数据,新数据不会覆盖旧ID数据
            this.dataMap.set(item.id, item)
          }
        })
      })
    },
    
//  方法二读取数据写入map  
if (this.dataMap.get(item.blockId) === undefined) {
          this.dataMap.set(item.blockId, temp)
        }



 streetChange() {
      //根据id获取get对象的值的对象不用写个遍历找数组中id等于这个的对象
      let obj = this.dataMap.get(this.form.yyy)
      // set form.street 必定出发change事件
      this.getStreetInfo()
    },