Iterate through dictionary/object more than 10 keys deep in CustomJS

Hi, I’m running into strange to me JS behaviour when trying to iterate through a dictionary passed to CustomJS. This is definitely a JS-side learning thing for me (and will probably expose my ignorance :joy: but that’s part of learning). In the callback, all I’m doing in this example is iterating through a dictionary that has more than 10 keys when triggered:

from bokeh.plotting import save
from bokeh.models import Select, CustomJS

opts=['A','B','C','D','E','F','G','H','I','J','K','L']
sel = Select(title='Thing:', options = opts)

d = {i:s for i,s in enumerate(opts)}

cb = CustomJS(args=dict(sel=sel,d=d)
              ,code='''
              console.log(d)
              for (const [key,value] in Object.entries(d)){
                      console.log(key)}
              
              ''')
sel.js_on_change('value',cb)
save(sel,'Test.html')

The strange (to me) behaviour when I do this is that the key being logged in the loop is only returning the first digit of the key:

I can’t recreate this writing out the same routine in JSFiddle:

This tells me bokeh is doing something to the dictionary when I pass it? It’s very strange to me because I would like to think I’d have run into this before… hopefully there is an obvious explanation.

As another check, I also tried replacing my dictionary d with a unique string for a key:

d = {'bananas_'+str(i):s for i,s in enumerate(opts)}

Results in the same kind of thing:

What’s going on?

Thanks…

Update, I found a workaround by simply iterating through Object.keys(d) instead… but my understanding is still completely missing.

You need for…of (like you have in the fiddle), not for…in

1 Like

…thank you. /embarassed

It’s happened to me more times than I can remember. Purely IMO, JavaScript is just an ugly, unpleasant language with lots of warts and gotchas around every corner, unfortunately.

1 Like