How to reliably hash JavaScript objects?

前端 未结 6 1853
天涯浪人
天涯浪人 2021-02-06 21:53

Is there a reliable way to JSON.stringify a JavaScript object that guarantees that the ceated JSON string is the same across all browsers, node.js and so on, given that the Java

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 22:41

    You might be interested in npm package object-hash, which seems to have a rather good activity & reliability level.

    var hash = require('object-hash');
    
    var testobj1 = {a: 1, b: 2};
    var testobj2 = {b: 2, a: 1};
    var testobj3 = {b: 2, a: "1"};
    
    console.log(hash(testobj1)); // 214e9967a58b9eb94f4348d001233ab1b8b67a17
    console.log(hash(testobj2)); // 214e9967a58b9eb94f4348d001233ab1b8b67a17
    console.log(hash(testobj3)); // 4a575d3a96675c37ddcebabd8a1fea40bc19e862
    

提交回复
热议问题