Last active
January 14, 2022 13:25
-
-
Save colelawrence/3b54f09bfdf4089f6e5c to your computer and use it in GitHub Desktop.
Create an md5 hash string of a javascript object using crypto createHash, update, and digest hex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var crypto = require('crypto'); | |
exports.hashObject = function (object) { | |
var hash = crypto.createHash('md5') | |
.update(JSON.stringify(object, function (k, v) { | |
if (k[0] === "_") return undefined; // remove api stuff | |
else if (typeof v === "function") // consider functions | |
return v.toString(); | |
else return v; | |
})) | |
.digest('hex'); | |
return hash; | |
} |
@dhwaneetbhatt – interesting... thanks for the note!
I have an idea of how this could be fixed by keeping the hash state in its own variable, then using the more common for x in obj
like loop.
At this point, (given I put this together 6.5 years ago), I'd probably question the goals of hashing an object anyways, is it for keeping a version?
If it's simply for serialization, then it's probably okay to JSON.stringify
for the database entry (if you can't use jsonb
), but if it's to sort of use as some kind of key, perhaps a simple Map / WeakMap might be more appropriate (and far more efficient).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JSON.stringify()
is not guaranteed to return keys in the same order.