How to populate dashboard dropdown button dynamically

I'm reviving this topic because I'm having trouble getting the options in the dropdown list to be dynamic. I'm trying to build a string for each choice, but what I'm doing here isn't working. Any advice is appreciated.

[{"id":"6a5ce82b.1fb528","type":"ui_dropdown","z":"10428117.fbe57f","name":"","label":"","tooltip":"","place":"Select option","group":"cdbf58bd.144278","order":23,"width":0,"height":0,"passthru":true,"multiple":false,"options":[{"label":"","value":"","type":"str"}],"payload":"","topic":"","x":910,"y":260,"wires":[[]]},{"id":"8b0e1b1c.884df8","type":"function","z":"10428117.fbe57f","name":"Populate Dropdown Options","func":"let dynamicOption;\nlet numberOfOptions = 5;\n\nlet choice = [];\n\nfor (let i = 0; i < numberOfOptions; i++) {\n    dynamicOption = \"Option \" + i;\n    \n    choice.push( { dynamicOption : i} );\n}\n\nmsg.options = choice;\n\n\nreturn msg;","outputs":1,"noerr":0,"x":640,"y":260,"wires":[["6a5ce82b.1fb528","6c2db2b7.00660c"]]},{"id":"cdfc651.21af698","type":"inject","z":"10428117.fbe57f","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":400,"y":260,"wires":[["8b0e1b1c.884df8"]]},{"id":"6c2db2b7.00660c","type":"debug","z":"10428117.fbe57f","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":880,"y":220,"wires":[]},{"id":"cdbf58bd.144278","type":"ui_group","z":"","name":"Utilities","tab":"57a8107c.24ef7","order":3,"disp":true,"width":"6","collapse":false},{"id":"57a8107c.24ef7","type":"ui_tab","z":"","name":"NOAH 18898","icon":"dashboard","disabled":false,"hidden":false}]

try this

choice.push( { [dynamicOption] : i} );

1 Like

Yes @yoyocarry 's code works. In this way we can create the option labels dynamically.

Only: Can somebody explain why it works? Why do the square brackets change the behavior of the
{key : value} expression?

Thanks a lot!

Because they change the property name to the value between the brackets;

let dynamicOption = "propertyKey"

let object = {[dynamicOption]: 10} 

// is the same as
// let object = {propertyKey: 10}