Home > Back-end >  Use arrays as keys for a dict
Use arrays as keys for a dict

Time:07-21

Note:
Asking about alternative methods for performing a task is not a matter of opinion. Asking about pros and cons of such methods is not a matter of opinion. This is what I am asking.
Asking which method is preferable, based on such pros and cons, is a matter of opinion. This is not what I am asking.


I mean to use a dict (or a similar object) in Google apps script, with arrays as keys. These (I didn't know) are converted to strings when used as dict keys.
The way I wrote my code, for what I needed, was working. After I added some functionality, the limitations surfaced. For instance, I want keys to be something like [<color>,<number>]. Then I mean to do

for (key in mydict) {
    var c = key[0];
    var n = key[1];
    ... work separately with c as a string and n as a number
}

I guess I could split key at the comma, and convert n to int, but if there is a less cumbersome alternative, I would go for that.

One solution I found is with WeakMap. I am currently trying it.

Regardless the fact it may work, is there any alternative? What are possible pros and cons of those other options?

It would be very good to know before rewriting all code.

CodePudding user response:

One simple option is

for (keystr in mydict) {
    var key = keystr.split(',');
    var c = key[0];
    var n = key[1];
    ... work separately with c as a string and n as a number
}

which works as long as none of the elements in the keys contains ','.

CodePudding user response:

Use nested objects.

mydict = {
    "color1": {
        1: <somevalue>,
        5: <othervalue>
    },
    "color2": {
        3: <value3>,
        10: <value4>
    }
};

Then use nested loops:

Object.entries(mydict).forEach(([c, item]) =>
    Object.entries(item).forEach([n, value]) => {
        // do something with c, n, value
    })
);
  • Related