问题:返回的非类型化对象可能有100多个不同的键。我想把所有的错误对象,不管是什么类型,都转换成一个对象。
const input = [
{
"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?"
}
]
}
]
预期输出=
{
"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?"
}
我目前的尝试(有效)看起来像这样。不过,我认为它可能不需要减少通话。有没有更简单的方法?
const returnVal = val.reduce((acc,curr) => {
return ([...acc.errors, ...curr.errors] as any).reduce((a: any, c: any) => ({...a, ...c}), {});
});
1条答案
按热度按时间vhmi4jdf1#
使用
Array.flatMap()
获取一个对象数组,然后通过扩展到Object.assign()
将它们合并为一个对象:对于TS,你需要给予对象一个通用类型,因为
errors
对象有随机属性(TS playground):