参考:
(37条消息) js数组对象交集_1default的博客-CSDN博客_js 对象数组取交集
(37条消息) JS中filter()方法的使用_PrinciplesMan的博客-CSDN博客_filter函数的用法
(37条消息) js 获取两个数组的交集,并集,补集,差集_windy-boy的博客-CSDN博客_js取两个数组的交集
var arr1 = [{ id1: 1 }, { id1: 2 }, { id1: 3 }]; var arr2 = [{ id: 7 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }]; var have = [] //定义一个空数组 arr1.forEach(el => { have.push(el.id1) //将数组一与数组二用于对比的字段放到一个数组中 // have=[7,2,3,4,5,6] }) console.log("have",have) // 然后就是用另一个数组使用filter来过滤满足条件的数据, 返回一个新的数组, // 使用indexOf来判断是否存在这个数据, 没有的话返回 - 1有的话就返回位置, 这里 != -1, 表示检索有这个数据的 // 两者结合就是检索arr1中的id1与arr2中的id相同的数据出来返回一个新的数组.间接实现数组对象的交集 var result = arr2.filter(function (e) { return have.indexOf(e.id) != -1 }) console.log(result)
涉及到的函数
实际vue.js里面的代码(自用)
var menuDicts_appKey = []
//菜单menuDicts用于对比的字段放到一个数组menuDicts_appKey中
this.menuDicts.forEach(el => {
menuDicts_appKey.push(el.appKey)
})
console.log("menuDicts_appKey", menuDicts_appKey)
// 取交集,对字典appDicts进行过滤,返回新的对象数组
// 核心:用indexOf来判断菜单appKey数组是否存在这个数据(dictValue)
// 两者结合就是检索appDicts中的appKey与menuDicts中的dictValue相同的数据出来返回一个新的数组.间接实现数组对象的交集
this.showDicts = this.appDicts.filter(function (e) {
return menuDicts_appKey.indexOf(e.dictValue) != -1
})
console.log(this.showDicts)
数据定义部分
data() {
return {
lineChartData: lineChartData.newVisitis,
appDicts: {},
menuDicts: {},
showDicts: [],
// 新增
rol_all: [],
rol_0: [],
rol_1: [],
rol_2: [],
rol_3: [],
queryParams: {
parentId: undefined,
status: undefined,
menuId: undefined
},
}
},
menuDicts_appKey.indexOf ()
menuDicts_appKey是数组的形式,不用定义在data里面