I’ve got an object like:
{
a : 'foo',
b : 'bar',
c : 'foo',
d : 'baz',
e : 'bar'
}
I want to reduce the duplicates like:
{
ac : 'foo',
be : 'bar',
d : 'baz'
}
What’s a good way to do that?
A few caveats:
- There will only ever be a small number of pairs. (Currently there are 7; I could imagine it going up to, say, 20.)
- The initial property names will only ever be a single character, like in the example
- The values could potentially run to several hundred characters.
- both speed and code-length are highly important, but given the small number of rows, code clarity is probably still most important.
Go through each property of the object and construct another object, where the keys are the values of the first, and the values are lists of keys (from the first). Then you go back through that second object and make the final result.
Something like this:
Now, if the values of the original object are not strings, then things get more involved: only strings can be property keys in a Javascript object. You could look around for a more general hash implementation, in that case. If your objects tend to be pretty small (fewer than 10 or so properties) you could write up the n2 version, where you simply iterate over the properties and then iterate again for each one. That would probably be a bad idea however if your objects might be large and you have to perform this operation a lot.