Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Last active January 14, 2022 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save colelawrence/3b54f09bfdf4089f6e5c to your computer and use it in GitHub Desktop.
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
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
Copy link

JSON.stringify() is not guaranteed to return keys in the same order.

@colelawrence
Copy link
Author

@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