Get original object when using raycaster.intersectObjects

When running the function intersectObjects with recursive set to true like so:

const objectsArray = [ object1, object2 ... ]
let intersects = raycaster.intersectObjects( objectsArray, true );

Is a way to get the original object from objectsArray that was intersected, if the returned object (intersects.object) is a child of the original object? Here is what I currently do:

const objectTree = [ intersects.object ];

intersects.object.traverseAncestors( ( object ) => {

	objectTree.push( object );

} );

const found = objectArray.filter( ( r ) => objectTree.includes( r ) ); // looks for common objects in two arrays, and returns array

I feel like there must be a better way. Wouldn’t it be useful if the original object is returned by the raycaster.intersectObjects() function (e.g intersects.orginalObject) ? I need to know which of the obejct in objectsArray is returned quite frequently, and I thought it might be worth writing a PR for this if there isn’t a better way.

Why not do this?

const objectsArray = [ object1, object2 ... ]
objectsArray.forEach(object => {
  let intersects = raycaster.intersectObjects( object, true );
});

If there are any intersections, you know it was for the original object.

I thought that worked for my case, but I am interested in the order in which the objects are intersected. I don’t get that information with the solution you propose.

Solution:

let object = intersects[0].object;
while ( object.parent && ! objectsArray.includes( object ) ) object = object.parent;
const originalObject = object;

A faster way, if all objects in objectsArray are tied directly to the scene:

let object = intersects[0].object;
while ( object.parent && object.parent.parent ) object = object.parent;
const originalObject = object;