Search code examples
javascripthashjavascript-objects

Creating a hash of data JS


I have some data set represented as array, which i want to put in an object as property. I want each property to be accessible by generated key. Number and type of elements in array is unknown. I want it to look something like that:

// array - array on unknown data

let object = {};

object[createUniqueKey(array)] = array;

// and later i want to use it the same way
console.log(object[createUniqueKey(array)])

Hope i've described well, thanks for help in advance


Solution

  • The easiest way to create a unique key to avoid having your object's data overwritten is to use a counter and increment it on every insertion. Alternatively, you could implement your own UUID-generating function, but I wouldn't go as far.

    Example:

    let object = {};
    let createUniqueKey = ((counter) => () => counter++)(0); 
    let array = ["a", "b", "c"];
    
    /* Create a unique key. */
    let key = createUniqueKey();
    
    /* Create a unique key to store the array. */
    object[key] = array;
    
    /* Use the key to get the array from the object. */
    console.log(object[key]);

    If instead, you want to use the array and based on that to create your key, the only solution that comes to my mind now is using a combination of toString and btoa (or simply the latter as it accepts array arguments). However, this method has some restrictions such as when the array contains objects and functions.

    Example:

    let object = {};
    let createKey = (array) => btoa(array);
    let array = ["a", "b", "c"];
    
    /* Create a key to store the array. */
    object[createKey(array)] = array;
    
    /* Use the array to recreate the key and access the array inside the object. */
    console.log(object[createKey(array)]);