const data = [ {
"name" : "test" ,
"children" : [ {
"name" : "test1" ,
"children" : [ {
"name" : "test11" ,
"children" : [ ]
} ]
} ,
{
"name" : "test2" ,
"children" : [ {
"name" : "test21" ,
"children" : [ {
"a" : "test211" ,
"b" : "uin"
} ,
{
"a" : "test212" ,
"b" : "fied"
} ,
]
} ]
} ,
{
"name" : "test3" ,
"children" : [ {
"a" : "test31" ,
"b" : "uin"
} ,
{
"a" : "test32" ,
"b" : "tkdg"
} ,
]
}
]
} ]
一、过滤指定数据
原始数据处理完后的结构为:(只保留 b 为 uin 类型的数据)
const data = [ {
"name" : "test" ,
"children" : [ {
"name" : "test1" ,
"children" : [ {
"name" : "test11" ,
"children" : [ ]
} ]
} ,
{
"name" : "test2" ,
"children" : [ {
"name" : "test21" ,
"children" : [ {
"a" : "test211" ,
"b" : "uin"
} ,
]
} ]
} ,
{
"name" : "test3" ,
"children" : [ {
"a" : "test31" ,
"b" : "uin"
} ,
]
}
]
} ]
function handleTagsTree ( children, filterKey, filterValue ) {
if ( ! filterKey || ! filterValue) {
return children;
}
const data = [ ] ;
children. forEach ( ( item ) => {
if ( item?. children && item?. children. length !== 0 ) {
item. children = handleTagsTree ( item. children, filterKey, filterValue) ;
}
data. push ( item) ;
} ) ;
return data. filter ( val => val[ filterKey] === filterValue || val?. children) ;
}
const processedData = handleTagsTree ( data, 'b' , 'uin' )
return data. filter ( val => val[ filterKey] === filterValue || val?. children && val. children. length) ;
const data = [ {
"name" : "test" ,
"children" : [
} ,
{
"name" : "test2" ,
"children" : [ {
"name" : "test21" ,
"children" : [ {
"a" : "test211" ,
"b" : "uin"
} ,
]
} ]
} ,
{
"name" : "test3" ,
"children" : [ {
"a" : "test31" ,
"b" : "uin"
} ,
]
}
]
} ]
二、提取指定数据(转换成新的数组输出)
原始数据处理完后的结构为:(把 b 这一层的数据提取出来形成一个新的数组)
[
{
"a" : "test211" ,
"b" : "uin" ,
} ,
{
"a" : "test212" ,
"b" : "fied" ,
} ,
{
"a" : "test31" ,
"b" : "uin" ,
} ,
{
"a" : "test32" ,
"b" : "tkdg" ,
} ,
]
function handleTagsTree ( children, filterKey ) {
if ( ! filterKey) {
return children;
}
let data = [ ] ;
children. forEach ( ( item ) => {
if ( item?. children && item?. children. length !== 0 ) {
item = handleTagsTree ( item. children, filterKey) ;
data = data. concat ( item) ;
}
if ( item. hasOwnProperty ( filterKey) ) {
data. push ( item) ;
}
} ) ;
return data;
}
const processedData = handleTagsTree ( data, 'a' )