js 数组的处理

js 数组的处理

    arr1 = [

{

label: '系统管理',

id: 2011,

children: [

{

label: '通讯录',

id: 2012

},

{

label: '个人资料',

id: 2014

}

]

},

{

label: '客户及商机管理',

id: 2024,

children: [

{

label: '线索库',

id: 2025,

children: [

{

label: "新建线索",

id: 2031

}

]

},

{

label: "商机库",

id: 2026,

children: [

{

label: "新建线索",

id: 2031

}

]

},

{

label: "客户",

id: 2040

}

]

}

]

需要得到:

    arr2 = [

{

label: '客户及商机管理',

id: 2024,

children: [

{

label: '线索库',

id: 2025,

children: [

{

label: "新建线索",

id: 2031

}

]

},

{

label: "商机库",

id: 2026,

children: [

{

label: "新建线索",

id: 2031

}

]

}

]

}

]

需要处理arr1 的第三级children有值就返回,没有就过滤掉


回答:

function filterData(data, level = 0){

function filterTreeData(data, level, zindex = 1){

return data.filter(item => {

if(zindex >= level){

return true

}else if(Array.isArray(item.children)){

let c = filterTreeData(item.children, level, zindex + 1)

if(c.length){

item.children = c

}

return c.length

}

})

}

data = JSON.parse( JSON.stringify(data) )

return filterTreeData(data, level, 1)

}

filterData(arr1, 3)


回答:

这种方法应该可以

function hasNext(item, level) {

if(level<=0) {

return true

}

let result = true;

while(--level) {

result = result && Array.isArray(item.children);

item

if(Array.isArray(item.children) && item.children.length) {

item = item.children[0]

}

}

return result;

}

arr1.filter(item => hasNext(item,3))

以上是 js 数组的处理 的全部内容, 来源链接: utcz.com/p/935713.html

回到顶部