将嵌套数组转换为对象,将数组索引与对象ID匹配

时间:2019-01-19 16:31:32

标签: javascript node.js reactjs redux

我目前正在使用redux减速器。

//backend response
const response = {
    data: {
        results: {
            222: {
                items: ['id1', 'id3']
            },
            333: {
                items: ['id2', 'id4', 'id999 (UNKNOWN)']
            }
        }
    }
};

//currently saved in redux state
const stateItems = [
    {
        id: 'id1',
        name: 'item ONE'
    }, {
        id: 'id2',
        name: 'item TWO'
    }, {
        id: 'id3',
        name: 'item THREE'
    }, {
        id: 'id4',
        name: 'item FOUR'
    }, {
        id: 'id5',
        name: 'item FIVE (UNUSED)'
    }, {
        id: 'id6',
        name: 'item SIX (UNUSED)'
    }
];


//converting items: ['ids'] => items: [{id: 'id', name: 'itemName'}]
const result = Object.values(response.data.results).map((keys, index, array) => {
    keys.items = keys.items.map(itemId => {
        return stateItems[stateItems.findIndex(x => x.id === itemId)];
    });

    return response.data.results;
});


//final result should be:
const expectedFinalResult = {
    222: {items: [{id: 'id1', name: 'item ONE'}, {id: 'id3', name: 'item THREE'}]},
    333: {items: [{id: 'id2', name: 'item TWO'}, {id: 'id4', name: 'item FOUR'}]}
};

//both should be equal:
console.log(JSON.stringify(expectedFinalResult));
console.log(JSON.stringify(result));
console.log('same result: ' + JSON.stringify(result) === JSON.stringify(expectedFinalResult));

我没有想法,如何实现它。 UNUSEDUNKNOWN也应过滤掉。这样,本示例中的最终结果就像const expectedFinalResult中的那样。当前const result返回了错误的结果。

希望有人有更好的主意和更好的方法。

谢谢

2 个答案:

答案 0 :(得分:0)

使用Object.entries使您处在正确的轨道上。您可以使用解构方法来选择键('222''333')和值对象的items数组,然后使用该数组过滤stateItems并生成{{1 }}结果中每个条目的数组:

items

实时示例:

const result = {};
for (const [key, {items}] of Object.entries(response.data.results)) {
    result[key] = {
        items: stateItems.filter(item => items.includes(item.id))
    };
}
//backend response
const response = {
    data: {
        results: {
            222: {
                items: ['id1', 'id3']
            },
            333: {
                items: ['id2', 'id4', 'id999 (UNKNOWN)']
            }
        }
    }
};

//currently saved in redux state
const stateItems = [
    {
        id: 'id1',
        name: 'item ONE'
    }, {
        id: 'id2',
        name: 'item TWO'
    }, {
        id: 'id3',
        name: 'item THREE'
    }, {
        id: 'id4',
        name: 'item FOUR'
    }, {
        id: 'id5',
        name: 'item FIVE (UNUSED)'
    }, {
        id: 'id6',
        name: 'item SIX (UNUSED)'
    }
];


const result = {};
for (const [key, {items}] of Object.entries(response.data.results)) {
    result[key] = {
        items: stateItems.filter(item => items.includes(item.id))
    };
}

//final result should be:
const expectedFinalResult = {
    222: {items: [{id: 'id1', name: 'item ONE'}, {id: 'id3', name: 'item THREE'}]},
    333: {items: [{id: 'id2', name: 'item TWO'}, {id: 'id4', name: 'item FOUR'}]}
};

//both should be equal:
console.log(JSON.stringify(result, null, 4));

这会使.as-console-wrapper { max-height: 100% !important; }多次通过。如果它或stateItems确实很大,真的非常大(例如成千上万),则可能值得在response.data.results的{​​{1}}中进行Map代替:

stateItem

实时示例:

id
// Create map of state items (only once each time stateItems changes):
const stateItemMap = new Map(stateItems.map(item => [item.id, item]));

// Map results (each time you get results):
const result = {};
for (const [key, {items}] of Object.entries(response.data.results)) {
    result[key] = {
        items: items.map(id => stateItemMap.get(id))
    };
}

答案 1 :(得分:0)

您可以通过reduce来实现:

Object.entries(response.data.results)
    .reduce((acc, [key, { items }]) => ({
        ...acc,
        [key]: { // we can use the dynamic keys to add in our accumulated object
            items: items
                .map(itemId => stateItems.find(x => x.id === itemId)) // you can use find directly instead of findIndex then access
                .filter(Boolean) // we skip the unneeded elements
        }
    }), {});