/**
 * @param {Array} dataList 完整数据(必传)
 * @param {Sting/Int} keyName 对哪个字段进行与targetID对比(必传)
 * @param {Sting/Int} targetID 目标数据的唯一标识符(必传)
 * @param {Sting/Int} fieldName 目标数据的某个字段的字段名(可缺省)
 * @return {Object/String/Int/Array} 返回的目标数据, 目标数据类型根据 fieldName 字段的类型确定,默认返回Object
 */
function functionRecursive({ dataList, keyName, targetID, fieldName }) {
 let target_data = {}
 let targetID_type = ['string', 'number']
 if (!Array.isArray(dataList) || !dataList.length) {
  alert('传入的数据格式需为数组且不能为空...')
  return target_data
 }
 if (!keyName || typeof keyName !== 'string') {
  alert('未传入对比字段名称...')
  return target_data
 }
 if (!targetID) {
  alert('未传入目标数据的唯一标识符...')
  return target_data
 }
 let ID_type = typeof targetID
 if (!targetID_type.includes(ID_type)) {
  alert('目标数据唯一标识符应为数字或字符串...')
  return target_data
 }
 // 递归过程
 let get_target_data = item => {
  if (item[keyName] == targetID) {
   target_data = item
  } else {
   if (item.children && item.children.length) {
    for (let i = 0; i < item.children.length; i++) {
     if (Object.keys(target_data).length) break // 如果已经找到了目标数据,记得break
     get_target_data(item.children[i])
    }
   }
  }
 }
 // for循环传入的 dataList 数据并开始递归
 for (let i = 0; i < dataList.length; i++) {
  if (Object.keys(target_data).length) break // 同上
  get_target_data(dataList[i])
 }
 // 返回目标数据
 if (fieldName && typeof fieldName == 'string') {
  if (target_data.hasOwnProperty(fieldName)) {
   return target_data[fieldName]
  } else {
   alert('字段名应为字符串或目标数据中无此字段...')
   return {}
  }
 } else {
  return target_data
 }
}
export default functionRecursive
调用示例(找到 this.tree_data 中 id 字段值为 13 的数据):
let data = {
    dataList: this.tree_data,
    keyName: 'id',
    targetID: 13,
    fieldName: '',
}
console.time('run-time')
let target_data = functionRecursive(data)
console.timeEnd('run-time')
console.log(target_data) // 目标数据

ps:this.tree_data数据参考上一篇文章。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。