美文网首页
JS 递归查找子数据

JS 递归查找子数据

作者: 抽疯的稻草绳 | 来源:发表于2021-08-26 15:12 被阅读0次

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>递归查找子数据</title>
</head>

<body>
 <script>
  const carr = [

   {
    "code": "000001",
    "agyTypeCode": "REGION",
    "children": [{
     "code": "01",
     "agyTypeCode": "1",
     "children": [{
      "code": "0101",
      "agyTypeCode": "1",
      "children": [{
       "finChfName": "推荐",
       "isPairAc": 1,
       "code": "0008",
       "name": "二胎",
       "agyCode": "0101",
       "id": "24d0cb01b02211e8b1528dc623111881",
       "acsCode": "001"
      }]
     }]
    }]
   }
  ]


  function find(arr, fn, result) {
   arr.forEach(item => {
    if (item.children) {
     find(item.children, fn, result)
    } else {
     if (fn(item)) {
      result.push(item)
     }
    }
   })
  }
  const result = []


  find(carr, item => {
   return item.name === '二胎' //查找的字段
  }, result)
  console.log(result)
 </script>
</body>

</html>
image.png

相关文章

网友评论

      本文标题:JS 递归查找子数据

      本文链接:https://www.haomeiwen.com/subject/obluiltx.html