写给女朋友的从treeData中递归查找某一项

101 阅读1分钟

代码如下

/** 通用的treeData递归查找某一项
 * @origin 原始数据默认[]
 * @childrenName children字段名称默认children
 * @fieldName 对比的字段名称默认id
 * @value 需要对比的值默认为空字符串
 */
export function TreeDataFindItem({
  origin = [],
  childrenName = 'children',
  fieldName = 'id',
  value = ''
}) {
  let item = null
  function loop(arr) {
    console.log(arr)
    for (let i = 0; i < arr.length; i++) {
      const x = arr[i]
      debugger
      if (x[fieldName] === value) {
        item = x
        break
      }
      if (Array.isArray(x[childrenName]) && x[childrenName].length) {
        loop(x[childrenName])
      }
    }
  }
  loop(origin)
  if (item) return item
  return null
}

使用方法

const item = TreeDataFindItem({
    origin: [{ id: 'aa', children: [{ id: 'bb' }] }],
    value: 'bb'
})
console.log(item)
// {id: 'bb'}