How to find the intersection and mark two multi-dimensional arrays

two deep arrays An and B with different levels of depth have the same ID. If they exist, mark them under the corresponding object in array A

.
var A= [{
        id: 1
    }, {
        id: 2,
        children: [{
            id: 3
        }, {
            id: 4
        }, {
            id: 5,
            children: [{
                id: 6
            }]
        }]
    }];
    var B= [{
        id: 1
    }, {
        id: 2,
        children: [{
            id: 5,
            children: [{
                id: 6
            }]
        }]
    }];
    let c = method(A,B)
    //
    c = [{
        id: 1,
        disabled:true
    }, {
        id: 2,
        disabled:true,
        children: [{
            id: 3
        }, {
            id: 4
        }, {
            id: 5,
            disabled:true,
            children: [{
                id: 6,
                disabled:true
            }]
        }]
    }];
Apr.08,2022

function method(A, B) {
  var ret = []
  A.forEach(itemA => {
    var r = B.find(itemB => itemB.id === itemA.id)
    var obj = Object.assign({}, itemA)
    ret.push(obj)
    if (r) {
      obj.disabled = true
      if (itemA.children && r.children) {
        obj.children = method(itemA.children, r.children)
      }
    }
  })
  return ret
}

if the quantity is small, it is acceptable to cross and traverse the tree constantly, and if you save the point of B, it can be accelerated for follow-up. The idea is for reference

function method (treeA, treeB) {
  return dfs(treeA, new Set(flat(treeB)))
}

function dfs (root, dict) {
  for (node of root) {
    if (dict.has(node.id)) {
      node.disabled = true
    }
    if (node.children) {
      dfs(node.children, dict)
    }
  }
  return root
}

function flat (root, path = []) {
  for (node of root) {
    path.push(node.id)
    if (node.children) {
      flat(node.children, path)
    }
  }
  return path
}
Menu