Problem: There are untyped objects returned with over 100 different possible keys. I aim to restructure all error objects, regardless of type, into a singular object.
const data = [
{
"type":"cat",
"errors":[
{
"keyA":"This is wrong!",
"keyB":"This is more wrong!!",
"keyC":"...horrible, just horrible"
}
]
},
{
"type":"dog",
"errors":[
{
"key1":"whoops",
"key2":"somebody has a typo"
},
{
"keyX":"umm...really?",
"keyY":"when did it start raining?"
}
]
}
]
expected result =
{
"keyA":"This is wrong!",
"keyB":"This is more wrong!!",
"keyC":"...horrible, just horrible",
"key1":"whoops",
"key2":"somebody has a typo",
"keyX":"umm...really?",
"keyY":"when did it start raining?"
}
My current solution (which is functional) appears as follows. However, I believe there may be a simpler approach that does not require additional reduce functions. Any suggestions?
const output = input.reduce((acc, curr) => {
return ([...acc.errors, ...curr.errors] as any).reduce((a: any, c: any) => ({...a, ...c}), {});
});