How to add all values from global table to a map variable?

How to add all values from global table to a map variable?

jkhedekar
Enthusiast Enthusiast
546 Views
1 Reply
Message 1 of 2

How to add all values from global table to a map variable?

jkhedekar
Enthusiast
Enthusiast

[ FlexSim 23.0.15 ]

I have a global table with bunch of columns and quite a few rows. I want to create a map from those. How can I do it in flexscript?

0 Likes
Accepted solutions (1)
547 Views
1 Reply
Reply (1)
Message 2 of 2

jason_lightfoot_adsk
Autodesk
Autodesk
Accepted solution

Below you can find the code for a user command - mapFromTable() - where you pass in the table and optionally columns you want to use as your map keys. If you don't pass in any columns then it will assume the first column holds the key values.

For example, with this data:

1715037234155.png

running

Map m=mapFromTable("GlobalTable1",["Name","Height"]);
return m[["Bob",175]].Zip;

will return 1234 - the shorter Bob's zip code;

The user command is:

/**Custom Code*/
Variant v=param(1);
Variant k=param(2);
Table t;
switch (v.type) {
    case VAR_TYPE_STRING: 
    case VAR_TYPE_NODE:  t=Table(v);break;
    case VAR_TYPE_POINTER: t=v;break;
    default:  msg("mapFromTable()", "Table type is "+v.type,1); return 0;
}
// Setup the key
Array keys=[t.getColHeader(1)];
if (parqty>1)
    keys=param(2);
// Set up the array of attributes from the other columns
Array attrCols=[];
for (int n=t.numCols;n>0;n--){
    if (keys.indexOf(n)<0 && keys.indexOf(t.getColHeader(n))<0)
    attrCols.push(t.getColHeader(n));
}
Map m;
Map attrs;
for (int r=t.numRows;r>0;r--){
    Array rowKeyArray=[];
    for (int k=1;k<=keys.length;k++){
        Variant val=t[keys];
        rowKeyArray.push(val);
    }
    Variant rowKey;
    if (rowKeyArray.length==1)
        rowKey=rowKeyArray[1];
    else
        rowKey=rowKeyArray;
    for (int n=attrCols.length;n>0;n--) {
        attrs[attrCols]=t[attrCols];
    }
    m[rowKey]=attrs.clone();
    attrs.clear();
}
return m.clone();

Auto-installing library attached.

mapFromTable_v3.fsl

Updated for the case where one key column is used, to no longer require the single key to be in an array: eg. myMap["Bob"] instead of previously requiring myMap[["Bob"]]

Update Feb'25 - was inconsistent when assigning a variant to be just one of its array values - fixed in v3.