Skip to content

Instantly share code, notes, and snippets.

@douglascayers
Created January 8, 2025 14:05
Show Gist options
  • Save douglascayers/79547958e8ea92b3c45e01a1db2e59c5 to your computer and use it in GitHub Desktop.
Save douglascayers/79547958e8ea92b3c45e01a1db2e59c5 to your computer and use it in GitHub Desktop.
Create hash of json object for certain keys
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