【前端】树状数组取出ID为3的项,方法越简单越好,求解

const floor = [

{

id: 1,

text: '一层',

children: [

{

id: 2,

text: '二层',

children: [

{

id: 3,

text: '三层',

children: [

{

id: 4,

text: '四层'

}

]

}

]

}

]

}

];

回答

let result = null;

const findItemById = (id, list = floor) => {

list.some(e => {

if (e.id === id) {

result = e;

return true;

} else {

if (e.children) {

result = findItemById(id, e.children);

if (result) {

return true;

} else {

return false;

}

}

}

})

return result;

}

console.log(findItemById(3))

看数据很有规律偷个懒

        function getId(id, obj = floor) {

for (let i = 1; i < id; i++) {

obj = obj[0]["children"]

}

return obj[0]

}

console.log(getId(3))

function getId (floor, id) {

for (const val of floor) {

return val.id === id ? val : val.children ? getId(val.children, id) : false

}

return false

}

console.log(getId(floor, 3))

用递归 简单易懂 支持无限极嵌套

const floor = [

{

id: 1,

text: '一层',

children: [

{

id: 2,

text: '二层',

children: [

{

id: 3,

text: '三层',

children: [

{

id: 4,

text: '四层'

}

]

}

]

}

]

}

];

const getById = (list, id) =>{

for(let i = 0; i < list.length; i++) {

if(list[i].id === id){

return list[i]

}else {

if(list[i].children){

return getById(list[i].children, id)

}

}

}

}

console.log(getById(floor, 3))

function findValue (arr) {

return arr[0].id === 3 ? arr[0] : findValue(arr[0].children)

}

console.log(findValue(floor))

function getNodeById(nodes, id) {

let result;

if(nodes && nodes.length) {

for(let i = 0, len = nodes.length; i < len; i++) {

let node = nodes[i];

/*

if(node.id === id) {

result = node;

break;

}else {

result = getNodeById(node.children, id);

if(result) break;

}

*/

result = node.id === id ? node : getNodeById(node.children, id);

if(result) break;

}

}

return result;

}

很简单,递归就完事了:

function func (floor) {

if (floor[0] && floor[0].children && floor[0].children[0].id === 3) {

return floor[0].children

}

return func(floor[0].children)

}

暂时只想到了递归,
返回项内删除了 child 内部的 child

function find(arr,id){

if(!arr){

return null;

}

let result=[];

function run(array_item){

array_item.forEach(item=>{

if(item.id===id){

var new_item = ({...item});//创建新对象 不影响原对象

delete new_item.children;//删除children,无需返回

result.push(new_item);

}

item.children&&run(item.children);

})

}

run(arr);

return result;

}

【前端】树状数组取出ID为3的项,方法越简单越好,求解

以上是 【前端】树状数组取出ID为3的项,方法越简单越好,求解 的全部内容, 来源链接: utcz.com/a/78701.html

回到顶部