How to find a object in a nested array using recursion in JS

后端 未结 7 830
慢半拍i
慢半拍i 2021-01-04 21:58

Consider the following deeply nested array:

const array = [
    {
        id: 1,
        name: \"bla\",
        children: [
            {
                id:         


        
7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 22:06

    You need to iterate through your objects and then need to be parse each object using recursion. Try the answer mentioned here: JavaScript recursive search in JSON object

    code:

    `function findNode(id, currentNode) { var i, currentChild, result;

    if (id == currentNode.id) {
        return currentNode;
    } else {
    
        // Use a for loop instead of forEach to avoid nested functions
        // Otherwise "return" will not work properly
        for (i = 0; i < currentNode.children.length; i += 1) {
            currentChild = currentNode.children[i];
    
            // Search in the current child
            result = findNode(id, currentChild);
    
            // Return the result if the node has been found
            if (result !== false) {
                return result;
            }
        }
    
        // The node has not been found and we have no more options
        return false;
    }
    

    }`

提交回复
热议问题