Multidimensional array traversal to get all id

there is a problem at present. To get all the id in a multidimensional array, the dimension of the array is uncertain. Although there are at most five layers, the loop is too bloated to write, and the recursive algorithm is not very familiar with

.
var arr = [
    {
      id: 1,
      type: "",
      children: [
          {
              id: 2,
              type: "",
              children: [
                  {
                      id: 3,
                      type: "",
                      children: [
                          {
                              id: 4,
                              type: "",
                              children: [...]
                          }
                      ]
                  }
              ]
          }
      ]
    }
]

how to get all the id in arr

Apr.16,2022

function setArr(arr, newArr) {
    newArr = newArr || [];
    arr.forEach(item => {
        (item.id || item.id == 0) && newArr.push(item.id);
        item.children && setArr(item.children, newArr);
    })
    return newArr;
}

there are two ways, and recursion is the most normal way.

there is, of course, an ingenious way to stringify the entire array, and then use regular matching to get all the id.


function getId(arr, newArr) {
                newArr = newArr || []
                for (let i = 0; i < arr.length; iPP) {
                    const item = arr[i];
                    if (item["id"]) {
                        newArr.push(item["id"])
                        if (item["children"]) {
                            getId(item["children"], newArr)
                        }
                    }
                }
                return newArr
            }

you can try closures

<?php   
$result = array_filter($arr, function ($var) {     
  $found = false;  
  array_walk_recursive($var, function ($item, $key) use (&$found) {    
    $found = $found || $key == "s";  
  });  
  return $found;  
});  

var_dump($result);

let idList = []
let arrBak = arr.concat()

while (arr.length) {
    let item = arr.shift()
    idList.push(item.id)
    arr = arr.concat(item.children)
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1c24666-336db.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1c24666-336db.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?