unique object identifier in javascript
Update My original answer below was written 6 years ago in a style befitting the times and my understanding. In response to some conversation in the comments, a more modern approach to this is as follows:
(function() {
if ( typeof Object.id != "undefined" ) return;
var id = 0;
Object.id = function(o) {
if ( typeof o.__uniqueid != "undefined" ) {
return o.__uniqueid;
}
Object.defineProperty(o, "__uniqueid", {
value: ++id,
enumerable: false,
// This could go either way, depending on your
// interpretation of what an "id" is
writable: false
});
return o.__uniqueid;
};
})();
var obj = { a: 1, b: 1 };
console.log(Object.id(obj));
console.log(Object.id([]));
console.log(Object.id({}));
console.log(Object.id(/./));
console.log(Object.id(function() {}));
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
console.log(k);
}
}
// Logged keys are `a` and `b`
Create a unique object identifier with javascript
You can use a Symbol.
Every symbol value returned from Symbol() is unique.
export class MyItem {
uniqueObjectIdentifier: symbol;
constructor(obj) {
this.uniqueObjectIdentifier = Symbol();
}
}
If browser support doesn't allow you to use a symbol, you can use a reference to an object instead.
export class MyItem {
uniqueObjectIdentifier: object;
constructor(obj) {
this.uniqueObjectIdentifier = {};
}
}
Is there a unique identifier for an object in javascript?
are there lower level unique characters being temporarily assigned to ob1 and ob2
Short answer: no, nothing that you'd be able to access.
By the way, the reason obj1
and obj2
are not equal in your example is because they're actually pointing to different places in memory. That's the only comparison that's being done (this is different than, say, JavaScript string comparison, which does not compare memory locations, but the value of the string itself).
JavaScript Object Id
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.
Javascript how to create unique id on object that is pushed into an array
simplelly call Math.floor(Math.random() * 10)
on every push and use spread syntaxs
// changed let to const cause it's not re-assigned
const dataArray = [];
for (let i = 0; i < randomNum; i++) {
// this copies the original data and overwrite key to a new randomly
// generated key
dataArray.push({ ...data, key: Math.floor(Math.random() * 10) });
}
How to return an array of unique objects based on the id of the object in es6?
Another one solution:
const arr = [{ id: 1, name: "PrimShal01", period: 3},{ id: 61, name: "TertDeep01", period: 1},{ id: 37, name: "SecoDeep01", period: 2},{ id: 49, name: "TertShal01", period: 1},{ id: 13, name: "PrimDeep01", period: 3},{ id: 61, name: "TertDeep01", period: 1}]
const result = Object.values(
arr.reduce((acc, obj) => ({ ...acc, [obj.id]: obj }), {})
);
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
What's the purpose of Symbol in terms of unique object identifiers?
I replied to your comment in the other question, but since this is open I'll try to elaborate.
You are getting variable names mixed up with Symbols, which are unrelated to one another.
The variable name is just an identifier to reference a value. If I create a variable and then set it to something else, both of those refer to the same value (or in the case of non-primitives in JavaScript, the same reference).
In that case, I can do something like:
const a = Symbol('a');const b = a;
console.log(a === b); // true
Related Topics
Differences Between Contenttype and Datatype in Jquery Ajax Function
How to Create a Hash or Dictionary Object in JavaScript
Jquery .Find() Doesn't Return Data in Ie But Does in Firefox and Chrome
Get Keys of JSON-Object in JavaScript
Input File to Array JavaScript/Jquery
Es6 Class Multiple Inheritance
How to Delete All Cookies with JavaScript
React.Js Replace Img Src Onerror
Deep Copy an Array in Angular 2 + Typescript
How to Have Jquery Restrict File Types on Upload
Is 'Window' Really Global in JavaScript
JavaScript Equivalent of Jquery's Extend Method
How to Serialize an Input File Object to JSON
Batchsize Field Name Ignored in Field Projection