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

问题描述 投票:0回答:1

问题:有超过 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}), {});
});
javascript typescript reduce
1个回答
1
投票

使用

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 as Object))

console.log(result)
© www.soinside.com 2019 - 2024. All rights reserved.