Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object Id

Do JavaScript objects/variables have some sort of unique identifier? Like Ruby has object_id. I don't mean the DOM id attribute, but rather some sort of memory address of some kind.

like image 559
treznik Avatar asked Jan 07 '10 13:01

treznik


People also ask

What is object ID in JS?

ObjectID() id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.

Do JavaScript objects have an ID?

No, objects don't have a built in identifier, though you can add one by modifying the object prototype.

How do I find the ID of an object?

Find User (Object ID) Select Users. Browse to or search for the desired user, then select the account name to view the user account's profile information. The Object ID is located in the Identity section on the right. Find role assignments by selecting Access control (IAM) in the left menu, then Role assignments.

How do you find the object of an object?

Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.


2 Answers

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array, // NOT a primitive value like string, number, etc. var objIdMap=new WeakMap, objectCount = 0; function objectId(object){   if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);   return objIdMap.get(object); }  var o1={}, o2={}, o3={a:1}, o4={a:1}; console.log( objectId(o1) ) // 1 console.log( objectId(o2) ) // 2 console.log( objectId(o1) ) // 1 console.log( objectId(o3) ) // 3 console.log( objectId(o4) ) // 4 console.log( objectId(o3) ) // 3 

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

like image 58
Phrogz Avatar answered Sep 19 '22 10:09

Phrogz


No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:

(function() {     var id = 0;      function generateId() { return id++; };      Object.prototype.id = function() {         var newId = generateId();          this.id = function() { return newId; };          return newId;     }; })(); 

That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a touch function as others have suggested.

like image 31
Xavi Avatar answered Sep 21 '22 10:09

Xavi