typescript 将多个对象数组转换为单个对象

axr492tv  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(250)

问题:返回的非类型化对象可能有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}), {});
});
vhmi4jdf

vhmi4jdf1#

使用Array.flatMap()获取一个对象数组,然后通过扩展到Object.assign()将它们合并为一个对象:

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?"}]}]

const result = Object.assign({}, ...input.flatMap(o => o.errors))

console.log(result)

对于TS,你需要给予对象一个通用类型,因为errors对象有随机属性(TS playground):

interface InputObject {
  type: string;
  errors: Record<string, string>[]
}

const input: InputObject[] = [{"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?"}]}]

const result = Object.assign({}, ...input.flatMap(o => o.errors))

console.log(result)

相关问题