// 例子 :
let tableData = [
{
id: 2,
common:'专用物料',
childList: [],
},
{
id: 3,
childList: [
{
id: 31,
common:'专用物料',
childList: [
{
id: 311,
common:'专用物料',
},
{
id: 321,
common:'通用物料',
},
],
},
{
id: 32,
common:'通用物料',
},
],
},
]
// 需要过滤出上面common为专用物料部分的值
filterArrByObj(tableData,'专用物料','childList','common')
// 过滤后的值为 :
[
{
id: 2,
common:'专用物料',
childList: []
},
{
id: 3,
childList: [
{
id: 31,
common:'专用物料'
childList: [
{
id: 311,
common:'专用物料'
}
]
}
],
},
]
// 形参 :
// arr:过滤的数据
// commonValue : 需要满足条件的对象value
// childList :树形子数组
// commonKey :需要满足条件的对象key
function filterArrByObj(arr,commonValue,childList,commonKey){
let arrCopy = []
arr.forEach((ele)=>{
if(ele[commonKey] === commonValue){
arrCopy.push(ele)
if(ele[childList]){
this.filterArrByObj(ele[childList], commonValue, childList,commonKey)
}
}
})
let num = arr.length
arrCopy.forEach(ele=>{
arr.push(ele)
})
for(let i = 0; i < num ; i++){
arr.shift()
}
},
js树形结构数组递归去掉不满足条件的元素
最新推荐文章于 2024-05-17 13:52:13 发布