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)]);