【发布时间】:2020-05-28 19:54:56
【问题描述】:
我需要以某种方式减少配置文件数组中的数据,以便最终对象根据最喜欢的电影和喜欢/收藏该电影的用户对配置文件 obj 中的数据进行分组。 我想要类似的东西:
{
'Forrest Gump': ["Nicholas Lain"],
'Planet Earth 1': ["Jane Jones", "Matthew Johnson"]
}
来自以下数据对象:
const profiles = [
{
id: 1,
userID: '1',
favoriteMovieID: '1',
},
{
id: 2,
userID: '2',
favoriteMovieID: '1',
},
{
id: 3,
userID: '4',
favoriteMovieID: '5',
}
];
const users = {
1: {
id: 1,
name: 'Jane Cruz',
userName: 'coder',
},
2: {
id: 2,
name: 'Matthew Johnson',
userName: 'mpage',
}
};
const movies = {
1: {
id: 1,
name: 'Planet Earth 1',
},
2: {
id: 2,
name: 'Selma',
}
};
我需要一些想法来重构以下代码,以便它返回到用户和电影对象,以从我在下面捕获的 ID 中获取他们的名字。我需要捕获名称,而不是 ID。
profiles.reduce(function (acc, obj) {
let key = obj['favoriteMovieID']
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj.userID)
return acc
}, {})
【问题讨论】:
标签: javascript arrays object higher-order-functions