The objects I use on the client side need a unique ID. My array of objects is very small, commonly 4 items, not more.
I use this:
export class MyItem {
uniqueObjectIdentifier: number;
constructor(obj) {
this.uniqueObjectIdentifier = Math.random();
}
}
Is there something maybe javascript or angular internal that I can access instead of the handcrafted property?
The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.
You will do have duplicates if you use only Date. now() in a loop, but Math. random() makes it unique.
No, objects don't have a built in identifier, though you can add one by modifying the object prototype.
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 = {};
}
}
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