将平面数据数组转换为Javascript中的嵌套对象

时间:2018-09-22 12:01:41

标签: javascript arrays object

其中filter1Prop对于相应的filter1ID总是相同的值,而filter2Prop对于相应的filter2ID总是相同的值,

我有一个具有以下结构的对象数组:

[{
    filter1ID: 'FLTR1ID1',
    filter1Prop: 'Property 1',
    filter2ID: 'FLTR2ID1',
    filter2Prop: 'Property 2',
},
{
    filter1ID: 'FLTR1ID1',
    filter1Prop: 'Property 1',
    filter2ID: 'FLTR2ID2',
    filter2Prop: 'Property 3',
}]

这需要转换为具有以下结构的对象数组(合并重复的属性):

[{
    id: 'FLTR1ID1',
    prop: 'Property 1',
    filter2: [
        {
            id: 'FLTR2ID1',
            prop: 'Property 2',
        },
        {
            id: 'FLTR2ID2',
            prop: 'Property 3',
        },
    ],
}]

我已经通过使用Array.prototype.reduce()并在输出对象值上进行如下映射来实现此目的:

const rowsToObject = rows => Object.values(rows.reduce((map, obj) => {
    map[obj.filter1ID] = map[obj.filter1ID] || {
        id: '',
        prop: '',
        filter2: {},
    };
    const filter1 = map[obj.filter1ID];

    filter1.id = obj.filter1ID;
    filter1.prop = obj.filter1Prop;
    filter1.filter2[obj.filter2ID] = filter1.filter2[obj.filter2ID] || {
        id: '',
        prop: '',
    };
    const filter2 = filter1.filter2[obj.filter2ID];

    filter2.id = obj.filter2ID;
    filter2.prop = obj.filter2Prop;

    return map;
}, Object.create(null))).map(result => ({
    ...result,
    filter2: Object.values(result.filter2),
}));

如果我只能处理一次输入数组中的每个条目,我会希望它。

有没有一种方法可以避免在不必对filter2数组进行查找操作的情况下最后使用Array.prototype.map()?

0 个答案:

没有答案