Search code examples
user-interfacedropdowndashboardnode-red

node-red dashboard - dropdown list problems


I am attempting to use node-red dashboard ui for an existing project. Within that I want to use the 'dropdown' as a selection mechanism. I obtain 'device' name and 'device_id' from an SQLite database, and I have used DEBUG messages to ensure this is happening correctly. As per dashboard dropdown information --

*"The Options may be configured by inputting msg.options containing an array. If just text then the value will be the same as the label, otherwise you can specify both by using an object of "label":"value" pairs : e.g. [ "Choice 1", "Choice 2", {"Choice 3": "3"}]

I have tried various methods to populate the 'options' array mentioned with the desired pairs however it does not appear to work as expected. The following code is an example using a function node:


var newmsg = msg;
newmsg.options = [];
var temp1, temp2;
for (var i = 0; i < msg.payload.length; i++) {
    temp1 = msg.payload[i].id;
    temp2 = msg.payload[i].name;
    newmsg.options[i] = {temp2 : temp1};
}
return newmsg;

( NB. temp1 and temp2 are because it won't parse within the single line assignment!)

this produces the following objects in the debug window:

topic: "select name, id from devices where 1;"
payload: array[186]
[0 … 9]
  0: object
    name: "Ron"
    id: 29
  1: object
    name: "Deck Motion TRx"
    id: 51
.
.
.
options: array[186]
  [0 … 9]
    0: object
      temp2: 29
    1: object
      temp2: 51
    2: object
      temp2: 54

. . . Can anyone tell me where I am going wrong?? Thanks


Solution

  • You are creating an object {temp2 : temp1} the property name will be temp2 and the value will be from temp1 variable. If you want to name a property to reflect a variable you need to use [] notation.

    For example:

    var name = "foo";
    var value = 20;
    
    var obj = {
        name : value
    }
    

    The output will be {"name":20}

    But if you use [] notation the object will be:

    var name = "foo";
    var value = 20;
    
    var obj = {};
    obj[name] = value;
    

    The object will be {"foo":20} As for your code, you could change it like this:

    var newmsg = msg;
    newmsg.options = [];
    var temp1, temp2;
    for (var i = 0; i < msg.payload.length; i++) {
        temp1 = msg.payload[i].id;
        temp2 = msg.payload[i].name;
        newmsg.options[i] = {};
        newmsg.options[i][temp2] = temp1;
    
    }
    return newmsg;