I'm trying to add an event to the bars in my graph. I tried this function bellow, but with this function it doesn't matter what bar I click, it will always return the last key in the array.
My guess would be this has to do with asynchronization, because it returns the last key value.
for (var key in data) {
  bar = bars.append('rect')
    .attr('class', 'bar')
    .attr('x', (dimensions.width / data.length) * currentId + 41)
    .attr('y', 100 - data[key] + 10).attr('height', data[key])
    .attr('width', dimensions.width / data.length)
    .attr('fill', '#4682B4')
    .on('click', (bar = key) => {
        console.log(key) //Always returns the same key
    });
  currentId++;
}
I have also tried to copy one of the keys the array contains and make a if-statement like this:
console.log(key === 1 ? true : false);
This will return true and false, exactly as it should. Another reason why I think this has to do with async.
My essential question is;
How can I make a click-event on this bar which will return the correct key
 
     
    