Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a unique object identifier with javascript

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?

like image 380
Elisabeth Avatar asked Jul 12 '17 18:07

Elisabeth


People also ask

How do I get a unique identifier?

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.

Is date now () unique?

You will do have duplicates if you use only Date. now() in a loop, but Math. random() makes it unique.

Do JavaScript objects have ids?

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


1 Answers

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 = {};
  }
}
like image 152
Ori Drori Avatar answered Sep 22 '22 18:09

Ori Drori