Natarajan Ganapathi
Natarajan Ganapathi

Reputation: 595

How to get Hash value of an object in Typescript?

How to get hash value of an object in typescript.

For example :

let user:any = {name:'tempuser', age:'29'};
let anotheruser:any = {name:'iam', age:'29'};
if( Object.GetHashCode(user) === Object.GetHashCode(anotheruser)){
   alert('equal');
}

also we can identify the object whether it is modified or not.

Upvotes: 12

Views: 55101

Answers (4)

Ronan-Yann Lorin
Ronan-Yann Lorin

Reputation: 339

I use the following function although I'm not sure if it is reliable:

function hashObject(object: Record<string, any>): string {
  if (typeof object != "object") {
    throw new TypeError("Object expected");
  }

  const hash = crypto
    .createHash("sha256")
    .update(JSON.stringify(object), "utf8")
    .digest("hex" as crypto.BinaryToTextEncoding);

  return hash;
}

Inspired from https://github.com/sindresorhus/hash-object/blob/main/index.js which may offer a better solution.

Upvotes: 0

Alan Wootton
Alan Wootton

Reputation: 81

For non-crypto uses, like implementing a hash table, here is is the typescript of the venerable java hashCode of a string:

export function hashCode(str: string): number {
    var h: number = 0;
    for (var i = 0; i < str.length; i++) {
        h = 31 * h + str.charCodeAt(i);
    }
    return h & 0xFFFFFFFF
}

Upvotes: 6

If you want to compare the objects and not the data, then the @Valery solution is not for you, as it will compare the data and not the two objects. If you want to compare the data and not the objects, then JSON.stringify(obj1) === JSON.stringify(obj2) is enough, which is simple string comparison.

Upvotes: 6

Val&#233;ry
Val&#233;ry

Reputation: 4708

AFAIK, neither JavaScript nor TypeScript provide a generic hashing function.

You have to import a third-party lib, like ts-md5 for instance, and give it a string representation of your object: Md5.hashStr(JSON.stringify(yourObject)).

Obviously, depending on your precise use case, this could be perfect, or way too slow, or generate too many conflicts...

Upvotes: 12

Related Questions