title: How to generate a key for a javascript object
body: <p>I want to implement an ObjectSet class, which contains a set of object references. In the implementation 1 below, I use an Array to store the objects. In the put/remove function, I iterate the whole array to find passed-in object. The set size would be very large and the functions are called frequently. The performance of the iteration is a concern.</p>
  
  <p>In the implementation 2, I use an Object, which acts as a map, to store the object references. In this manner, it doesn't need to iterate all the objects in the put/remove functions. The performance would be better. But the Object property must be a string. I can't use the object as the key. The question is: <strong>Is there any algorithm to generate a unique key for an object?</strong></p>
  
  <p><strong>Implementation 1 - Store object references in an Array</strong></p>
  
  <pre><code>function ObjectSet() {
      this.store = []; // Array
  }
  ObjectSet.prototype = {
      put: function( obj) {
          var store = this.store;
          for (var i = 0; i &lt; store.length; i++) {
              if (store[i] === obj) {
                  return;
              }
          };
      },
      remove: function( obj ) {
          var store = this.store;
          for (var i = 0; i &lt; store.length; i++) {
              if (store[i] === obj) {
                  store.splice(i, 1);
              }
          };
      }
  };
  </code></pre>
  
  <p><strong>Implementation 2 - Store object references in an Object</strong></p>
  
  <pre><code>function ObjectSet() {
      this.store = {}; // Object
  }
  ObjectSet.prototype = {
      put: function( obj) {
          var key = generateKeyFromObject(obj);
          if(!this.store[ key ]){
              this.store[ key ] = obj;
          }
      },
      remove: function( obj ) {
          var key = generateKeyFromObject(obj);
          if(this.store[ key ]){
              delete this.store[ key ];
          }
      }
  };
  function generateKeyFromObject(obj){
      // Question: How to generate a unique key for an object?
  }
  </code></pre>
  
  <p>============UPDATE 7/2/2014================</p>
  
  <p>Paste my implementation based on the answers/comments.</p>
  
  <pre><code>// Use the global index to avoid the clash when the same object is added to different sets.
  var index = 1, key='##key';
  function generateKeyFromObject(obj){
      if(!obj[key]){
          var uniqueKey="##uniqueKey" + (index++).toString();
          Object.defineProperty(obj, key, {
              writable: false,
              enumerable: false,
              configurable: false,
              value: uniqueKey
          });
     }
      return obj[key];
  }
  </code></pre>