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.
ObjectID() id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.
No, objects don't have a built in identifier, though you can add one by modifying the object prototype.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With