简体   繁体   中英

How do I make a “composite key” (and what is this even called)?

I have two key strings, representing two objects of two different classes of objects. The keys are unique within their classes. I need to create a unique key representing the combination of these two keys. How do I do this?

I can't just concatenate them, because any character could be present in the base keys. I could maybe escape the concatenation delimiter before I concatenate? I could create a hash of the two keys, but this feels heavy.

Are there built in functions to help me do this? Is this "called something"? It seems like this would be a common (solved) problem.

(I'm looking for this specifically in Javascript, but I'm curious about higher level solutions or frameworks as well)

Create a third type of object that has it's own key (or not, the key is optional) to track all the combinations. If you are dynamically creating these entries you may want something to check and enforce the uniqueness of the values.

I usually call this a crosswalk table or a linking table.

The wiki page covering this topic calls it an Associative Entity Wikipedia - Associative entity

Simply concatenate the two strings, but prefix the first string with its length, and a separator. For example, if the input strings are "cat" and "doorbell" , the output string would be "3:catdoorbell" . On the other hand, if the inputs were "catdoor" and "bell" , the output would be "7:catdoorbell" .

With this method, the outputs are unique, and the original keys are recoverable from the output string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM