Created
January 8, 2025 14:05
-
-
Save douglascayers/79547958e8ea92b3c45e01a1db2e59c5 to your computer and use it in GitHub Desktop.
Create hash of json object for certain keys
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
import crypto from 'crypto'; | |
const createHashFromKeys = (options: { | |
object: Record<string, any>; | |
keys: string[]; | |
algorithm?: string; | |
}): string => { | |
const { object, keys, algorithm = 'sha256' } = options; | |
const content = keys | |
.sort() | |
.map((key) => JSON.stringify(object[key])) | |
.join(''); | |
const hash = crypto.createHash(algorithm).update(content).digest('hex'); | |
return hash; | |
}; | |
// Example usage | |
const object = { | |
id: '123', | |
name: 'example', | |
data: { | |
a: { | |
b: { | |
c: 'value', | |
}, | |
}, | |
}, | |
}; | |
const keys = ['id', 'name', 'data']; | |
const hashSignature = createHashFromKeys({ object, keys }); | |
console.log(hashSignature); // Outputs the hash signature |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment