DEV Community

George Jempty
George Jempty

Posted on

Implementing Javascript Objects with Multi-part Keys

If you've done Javascript development for any period of time, you've likely encountered a situation where you've wanted the key for an object to be composed of multiple values. I've googled for relevant Javascript examples but they all seem to come up with associating multiple values with one key, that's not what I mean.

Rather, perhaps you want to compose an Object key from the values "foo" and "bar". A naive approach might be to concatenate the values with a delimiter unlikely to appear in the string, for instance the tilde, in which case you might create the key: "foo~bar".

Depending on the data though there could be the possibility that one of the values needed for the key could contain the delimiter you have chosen, and this will make it difficult to use the object's keys for some subsequent purpose, e.g if you thought you'd have a two-part key, and split it on the delimiter, you could end up with more than two values. Luckily there is another solution...

Put the values for the multi-part key into an array, then call JSON.stringify on it, and use the result for the array key:

const key = JSON.stringify(['foo','bar']); // '["foo","bar"]'

If you don't care about the order and want to treat ['bar', 'foo'] the same way as ['foo', 'bar'], sort the array you pass to JSON.stringify: ['foo','bar'].sort()

See the following answer I posted on StackOverflow this morning using this technique:

Top comments (0)