Say I have the following JavaScript objects:
const obj1 = {
key1: 'str1',
key2: 'str2'
}
const obj2 = {
key2: 'str2',
key1: 'str1'
}
const obj3 = {
key1: 'something else',
key2: 'str2'
}
const obj4 = {
differentKey: 'str1',
key2: 'str2'
}
I’d like to create a unique key based on a given object. This is so I can properly cache some data related to each object. In this scenario, obj1
and obj2
should have the same key, as the only difference is the ordering of properties. obj3
and obj4
should have different keys from each other. I tried using JSON.stringify()
but this gives different results for obj1
and obj2
due to the ordering. Is there a way to get around this, ideally that can work with non-primitive types?
2
Answers
I think you could cast your objects to an array, sort it by keys and re-cast it to your original object type. Then you‘d have the similar order of keys and can go ahead to hashing.
Here a more extensive answer from a similar question (not written by me)
https://stackoverflow.com/a/1069840/20932276
Here’s a function that recursively sorts nested objects by key. Then you can use
JSON.stringify
to create the unique keys.Feel free to fine tune the object type check (
isObject
) to fit your needs.