数组对象去重方法

数组对象去重(new Map方法)

new Map方法

data() {
    return {
 	// 导出列表
      exportList:[
  	{fileName:"XXXX", fileStatus:"已完成", fileTime:"2022-12-19 10:48:26", fileSize:"1256513345"},
	{fileName:"XXXX", fileStatus:"已完成", fileTime:"2022-12-19 10:48:26", fileSize:"1256513345"},
	{fileName:"1111", fileStatus:"执行中", fileTime:"2022-12-19 10:48:26", fileSize:"1256513345"},
	{fileName:"1122", fileStatus:"执行中", fileTime:"2022-12-19 10:48:26", fileSize:"1256513345"},
],
      newExportList:[], // 新列表 用于存放去重后的数据
    }
  },
methods: {
  getList() {
	// 数组对象去重
        let map = new Map();  // 保存键值对,并且能够记住键的原始插入顺序。
        for (let item of this.exportList) {
		// map.has()返回一个布尔值,用来表明 Map 对象中是否存在与指定的键 key 关联的值。
            if (!map.has(item.fileName)) { 
		//  map.set()在 Map 对象中设置与指定的键 key 关联的值,并返回 Map 对象。
                map.set(item.fileName, item); 
            };
        };
	// map.values()返回一个新的迭代对象,其中包含 Map 对象中所有的值,并以插入 Map 对象的顺序排列。
        this.newExportList = [...map.values()]; 
	colsole.log(this.newExportList)
  }
}

For循环 + indexOf

/**
 * @param {*} tempArr
 * @returns
 * tempArr:需要去重的对象
 */
const removeDuplicates = tempArr => {
  const newArr = []
  for (let i = 0; i < tempArr.length; i++) {
    if (newArr.indexOf(tempArr[i].companyName) === -1) {
      newArr.push(tempArr[i].companyName) // companyName为需要以xx去重
    } else {
      tempArr.splice(i, 1)
    }
  }
  return tempArr
}

标题:数组对象去重方法
作者:mcwu
地址:http://mcongblog.com/articles/2023/06/14/1686709458206.html

    评论
    0 评论
avatar

取消