Moving certain meshes from GLTF into groups

Hi,

I’ve got certain items in a GLB file that I need to animate their opacity in sections, so my thinking was to traverse each item in the loaded asset, check if the name matches certain keywords I’ve put into an array, and then if it finds each one of those, pull them out of the main object and put it into it’s own group, so that I can then target each group as I want to change opacity

loader.load("path/to/my/environment_model.glb", function(gltf) {
    const environment = gltf.scene;

    scene.add(environment);

    environment.traverse(child => {
      if (uniqueObjects.indexOf(child.name) > -1) {
        let group = new THREE.Group();
        group.name = child.name;
        console.log(group.name);
        // Up to here seems to work as I'd expect

        group.add(child);
        scene.add(group);
        environment.remove(child);
        // This is what I'd presume the code would be
      }
    });
}

If I run the code above, I get this error

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'traverse')

If I had to guess it looks like the last few lines of code are adding another item within the environment object for it to traverse though, but it doesn’t know what they are. It also then seems to be skipping every other item in my array as well, so I’m just really a bit confused

I actually think I’ve got it, I think I was looking at it from the wrong direction, instead of looping through everything in my mesh using the traverse method, I just looped through the items in the scene after they’ve all been added

$.each(uniquePulses, function( key, value ) {
  if (scene.getObjectByName(value) !== null) {
    let uniqueGroup = new THREE.Group({ name: value });
    let pulse = scene.getObjectByName(value);
    let childMesh = pulse.clone();
    let pulseParent = pulse.parent;

    uniqueGroup.add(childMesh);
    pulseParent.remove(pulse);

    scene.add(uniqueGroup);
  }
});

I read from this link that you’ve gotta call remove() from it’s direct parent, so I’m not 100% if this code is optimised, but it seems to be working, although it hasn’t kept the position of each item before it got removed, not a huge deal, I can probably figure it out