求帮解决一个JS 递归的 查找值的问题

需求:递归从下面的数据中找到某一个值。
例如:传入a1 ,找到a1所有在位置,并添加一个属性 expand: true,
因为后台返回的数据层级不确定,得要递归才可以。

export const json = [{
    "name": "测试1",
    "children": []
  },
  {
    "name": "测试2",
    "children": [{
        "name": "A区",
        "children": [{
            "name": "a1",
            "children": null
          },
          {
            "name": "a2",
            "children": null
          },
        ]
      },
      {
        "name": "B区",
        "children": [{
            "name": "b1",
            "children": null
          },
          {
            "name": "b2",
            "children": null
          },
        ]
      }
    ]
  },
]
阅读 4.4k
5 个回答
function findTarget(source, targetName) {
  if (source && source.length) {
    for (let item of source) {
      if (item.name === targetName) {
        item.expand = true;
      } else if (item.children && item.children.length){
        findTarget(item.children, targetName);
      }
    }
  }
}

findTarget(json, "a1");

function addExpand(arr, find){
  for(let k in arr){
   let item = arr[k]
   if(typeof item === 'object'){
      addExpand(item, find);
    } else{
      if (item == find) {
         arr.expand = true
      }
    }
  }
  return arr
}

let nJson = addExpand(json, 'a1')
function search(obj, name, namePath = []) {
  for (let i = 0, len = obj.length; i < len; i++) {
    let item = obj[i]
    if (item.name === name) {
      namePath.push(name)
      item.expand = true
      return {
        has: true,
        namePath
      }
    } else if (item.children && item.children.length) {
      namePath.push(item.name)
      let result = search(item.children, name, namePath)
      if (result.has) return {has: true, namePath}
      namePath.pop()
    }
  }
  return {
    has: false
  }
}

console.log(search(json, "测试2")) // {has: true, namePath: ["测试2"]}
console.log(search(json, "A区")) // {has: true, namePath: ["测试2", "A区"]}
console.log(search(json, "a2")) // {has: true, namePath: ["测试2", "A区", "a2"]}
console.log(search(json, "b2")) // {has: true, namePath: ["测试2", "B区", "b2"]}
console.log(search(json, "c2")) // {has: false}
function recursive(data,name){
    data.map(function(item){
        if(item.name !== name &&item.children && item.children.length){
            recursive(item.children, name);
        }
        else if(item.name === name){
            item.expand = true;
        }
        else{}
    })
}

使用数组解构似乎更方便。

let [, {children: [{children}]}] = json
let index = children.findIndex(obj => obj.name === 'a1')
children[0].expand = true

是不是很简单,捂脸逃走。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题