简体   繁体   English

基于键和值分组的 JavaScript 对象数组

[英]JavaScript array of objects grouping based on key and value

 let data = [ {news: id1, users: [{user1}, {user2}, {user3}]}, {news: id2, users: [{user2}, {user4}, {user6}]}, {news: id3, users: [{user1}, {user2}, {user4}]} ]

So from the above data, I need to be able to group news items to form a template(let's consider a template consists strictly two news items).因此,根据上述数据,我需要能够将新闻项目分组以形成模板(让我们考虑一个模板严格由两个新闻项目组成)。 Then for every template, I need to match the corresponding user.然后对于每个模板,我需要匹配相应的用户。 Finally, when I'm done with creating all the templates I need to map remaining users to their respective news items.最后,当我完成所有模板的创建后,我需要将剩余的用户映射到他们各自的新闻项目。

I've added a sample output below我在下面添加了一个示例输出

 [id1,id2] : [user2] [id2, id3] : [user2, user4] [id3, id1] : [user1, user2] [id2] : [user6] [id1] : [user3]

How do I achieve this?我如何实现这一目标?

You could take a hash table and build the wanted structure by checking the length of the values and if greater than 2 take the combination of the values for adding the new grouups to the result set, instead of the given group.您可以使用哈希表并通过检查值的长度来构建所需的结构,如果大于 2,则采用值的组合将新组添加到结果集中,而不是给定的组。

 var data = [{ news: 'id1', users: ['user1', 'user2', 'user3'] }, { news: 'id2', users: ['user2', 'user4', 'user6'] }, { news: 'id3', users: ['user1', 'user2', 'user4'] }], cool = data.reduce((r, { news, users }) => users.reduce((o, user) => ((o[user] = o[user] || []).push(news), o), r), {}), result = Object.entries(cool).reduce((r, [user, news]) => { function add(k, v) { var temp = r.find(([a]) => a.join('|') === v.join('|')); if (!temp) r.push(temp = [v, []]); temp[1].push(k); } if (news.length > 2) { news.reduce((r, v, i, a) => r.concat(a.slice(i + 1).map(w => [v, w])), []) .forEach(news => add(user, news)); } else { add(user, news); } return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM