Let's say I have a data object:
{
apple: 3,
apple-02: { // stuff },
apple124: 'morestuff',
banana: 5,
bananaPhone: 'morestuff',
cherry: 10,
}
I want to group the keys in that data object by the longest common prefix of those keys:
{
apple: {
apple: 3,
apple-02: { // stuff },
apple124: 'morestuff',
},
banana: {
banana: 5,
bananaPhone: 'morestuff',
},
cherry: { cherry: 10 }
}
So far I have this but I'm not entirely sure this works or is the best way to do this. If there's a smarter and more accurate way to do this please let me know:
Object.keys(data).reduce((accumulator, key) => {
const existingKey = Object.keys(accumulator).find(k => key.includes(k))
if (existingKey) {
return { ...accumulator, [existingKey]: { ...accumulator[existingKey], [key]: data[key] } }
}
return { ...accumulator, [key]: { [key]: data[key] } }
}, {})