gpt4 book ai didi

javascript - 展平对象中的数组

转载 作者:行者123 更新时间:2023-12-04 01:05:48 24 4
gpt4 key购买 nike

我有一个对象如下:

const USER_MAP = {
PREMIUM: ['a', 'b'],
RETAIL: ['c', 'd']
};

我想转换到下面

[
{ segment: 'PREMIUM', id: 'a' },
{ segment: 'PREMIUM', id: 'b' },
{ segment: 'RETAIL', id: 'c' },
{ segment: 'RETAIL', id: 'd' }
]

我想出了一个解决方案,如下所示

const USER_MAP = {
PREMIUM: ['a', 'b'],
RETAIL: ['c', 'd']
};


const userList = Object.entries(USER_MAP).reduce((accumulator, currentValue) => {
const userListByType = currentValue[1].map(id => ({ id, segment: currentValue[0]}))
return [...accumulator, ...userListByType]
}, []);

console.log(userList);

它有效,但我想知道是否有更好的方法来实现上述目标?就可读性而言,因为我在 reduce 中嵌套了一个 map,在我看来,我可能会把这里的东西复杂化

最佳答案

你可以拿Array#flatMap带有外键的嵌套对象的映射。

const
USER_MAP = { PREMIUM: ['a', 'b'], RETAIL: ['c', 'd'] },
result = Object
.entries(USER_MAP)
.flatMap(([segment, a]) => a.map(id => ({ segment, id })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 展平对象中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66530633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com