经常遇到这样一个需求,当前列表展示的内容存在一个数组里,然后有时候需要对这个数组进行筛选,不显示已经操作过的数据,比如:对管理员身份进行登记,一个管理员可以有多个身份,对于已经选择过的身份,在操作同一个管理员时不能再次显示。只是一个简单的数组筛选,每次都让我很头疼。
话不多说先上代码:
// 需求很简单 targetTable 里如果有 pid 与 startTable pid 一致的移除 startTable 对应对象返回新 startTable
let startTable = [
{pid: ‘3309’, rid: ‘2176430812823’, moduleName: ‘getClass’, userName: ‘songsili’},
{pid: ‘3310’, rid: ‘2176430812824’, moduleName: ‘webIndex’, userName: ‘zhangsan’},
{pid: ‘3312’, rid: ‘2176430812825’, moduleName: ‘dymanic’, userName: ‘wangwu’},
{pid: ‘3313’, rid: ‘2176430812826’, moduleName: ‘front’, userName: ‘lisi’},
{pid: ‘3314’, rid: ‘2176430812827’, moduleName: ‘static’, userName: ‘liunneg’},
{pid: ‘3315’, rid: ‘2176430812828’, moduleName: ‘former’, userName: ‘mengcan’},
{pid: ‘3316’, rid: ‘2176430812829’, moduleName: ‘pickUp’, userName: ‘lican’}
]
let targetTable = [
{pid: ‘3313’, forEvery: ‘sdfdsgsdfsd’, count: ‘1’, dateLimit: ‘2’},
{pid: ‘33015’, forEvery: ‘iiuskewrtrt’, count: ‘2’, dateLimit: ‘15’}
]
console.log(startTable)
// 第一种写法
targetTable.forEach(param => {
// 每次循环找到对应下标然后移除
let indexNum = 0
let targetNum = 0
startTable.forEach(paramS => {
if (param.pid === paramS.pid) {
targetNum = indexNum
}
indexNum++
})
startTable.splice(targetNum, 1)
})
console.log(startTable)
然而这份代码写的很艰辛,因为我知道如果在循环的时候操作当前数组,下标不发生变化的时候,数组操作会出现遍历不完整的情况,所以我先保存了一份匹配到的数组,然后再对原数组进行操作,splice操作只需要找到下标即可,includes是匹配对象是否一致,我匹配的只是某个字段是否一致
// 需求很简单 targetTable 里如果有 pid 与 startTable pid 一致的移除 startTable 对应对象返回新 startTable
let startTable = [
{pid: ‘3309’, rid: ‘2176430812823’, moduleName: ‘getClass’, userName: ‘songsili’},
{pid: ‘3310’, rid: ‘2176430812824’, moduleName: ‘webIndex’, userName: ‘zhangsan’},
{pid: ‘3312’, rid: ‘2176430812825’, moduleName: ‘dymanic’, userName: ‘wangwu’},
{pid: ‘3313’, rid: ‘2176430812826’, moduleName: ‘front’, userName: ‘lisi’},
{pid: ‘3314’, rid: ‘2176430812827’, moduleName: ‘static’, userName: ‘liunneg’},
{pid: ‘3315’, rid: ‘2176430812828’, moduleName: ‘former’, userName: ‘mengcan’},
{pid: ‘3316’, rid: ‘2176430812829’, moduleName: ‘pickUp’, userName: ‘lican’}
]
let targetTable = [
{pid: ‘3313’, forEvery: ‘sdfdsgsdfsd’, count: ‘1’, dateLimit: ‘2’},
{pid: ‘33015’, forEvery: ‘iiuskewrtrt’, count: ‘2’, dateLimit: ‘15’}
]
// 第二种写法
console.log(startTable)
let nowList = startTable.filter(items => {
var uaExist = true
targetTable.forEach(arr => {
if (arr.pid === items.pid) uaExist = false
})
if (uaExist) return items
})
console.log(nowList)
我推荐使用这种写法筛选并不会破坏原数组,重新赋值即可
操作数组我是很熟悉,但是在前端操作,和后端代码是有一定区别的,只能说类似
共同学习,写下你的评论
评论加载中...
作者其他优质文章