typescript 如何在Typescript中获取对象的哈希值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36811284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:25:50  来源:igfitidea点击:

How to get Hash value of an object in Typescript?

typescriptecmascript-6

提问by Natarajan Ganapathi

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.

我们也可以识别对象是否被修改。

回答by Valéry

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

AFAIK,JavaScript 和 TypeScript 都没有提供通用的哈希函数。

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

您必须导入第三方库,例如ts-md5,并为其提供对象的字符串表示形式: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...

显然,根据您的具体用例,这可能是完美的,或者太慢,或者产生太多冲突......

回答by Muhammad Ishtiaq Hussain

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.

如果您想比较对象而不是数据,那么@Valery 解决方案不适合您,因为它将比较数据而不是两个对象。如果你想比较数据而不是对象,那么 JSON.stringify(obj1) === JSON.stringify(obj2) 就足够了,这是简单的字符串比较。