I would bind data with elements
First I select my elements
let trainSelect = svg.selectAll(\'.train-w-dir\');
When I console.log
The key function is evaluated twice: once per each element of the selection and once per each datum. In the words of the docs (emphasis mine):
This key function is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]); the returned string is the element’s key. The key function is then also evaluated for each new datum in data, being passed the current datum (d), the current index (i), and the group’s new data, with this as the group’s parent DOM element; the returned string is the datum’s key.
In the first run when evaluated for each selected element d
will be undefined if you have not yet bound data to the elements.
It is not clear from the code you provided what might be the best solution to your problem. You could either provide a safe-guard against undefined values in the key function or, probably better, rebuild the way you bind data to your elements.
Related: Join existing elements of the DOM to data with d3.js