我有这个JSON
{
"people": [{
"games": [
"destiny",
"horizon",
"fifa",
"cuphead"
],
"name": "Cartman"
},
{
"games": [
"fifa",
"pes"
],
"name": "Kyle"
},
{
"games": [
"cuphead",
"destiny"
],
"name": "Stan"
},
{
"games": [
"pokemon",
"metroid"
],
"name": "Clyde"
},
{
"games": [
"fifa",
"metroid",
"pes"
],
"name": "Butters"
}
]
}
我需要让至少有两个游戏共享的用户,所以对于这个JSON,结果将是:
卡特曼和斯坦扮演命运和杯头
Kyle和Butters扮演FIFA和Pes
注意:Clyde将不在结果中,因为只有一场比赛与其他球员匹配
我想过两个解决方法
1-有一个字典使用两个标签(涵盖所有可能性)作为一个密钥并填写它如果它不存在和其他密钥匹配后,我会知道已经有两个匹配
2-让第一个用户将其与其他用户进行比较,如果匹配至少两个,则将其打印,然后继续下一个并与其他人进行比较等等
感谢任何帮助
答案 0 :(得分:0)
方法通过检查是否只有一个存在来减少游戏/人员,然后删除另一个对象的响应部分。
它返回的项目多于一项,但超过两项。
要获得结果,您可以删除包含两个部分的结果并调整其余部分。
var object = { people: [{ games: ["destiny", "horizon", "fifa", "cuphead"], name: "Cartman" }, { games: ["fifa", "pes"], name: "Kyle" }, { games: ["cuphead", "destiny"], name: "Stan" }, { games: ["pokemon", "metroid"], name: "Clyde" }, { games: ["fifa", "metroid", "pes"], name: "Butters" }] },
peoples = {},
games = {},
change = false;
object.people.forEach(function (person) {
person.games.forEach(function (game) {
games[game] = games[game] || {};
games[game][person.name] = true;
peoples[person.name] = peoples[person.name] || {};
peoples[person.name][game] = true;
});
});
do {
change = false;
Object.keys(games).forEach(function (k) {
var keys = Object.keys(games[k]);
if (keys.length === 1) {
delete peoples[keys[0]][k];
delete games[k];
change = true;
}
});
Object.keys(peoples).forEach(function (k) {
var keys = Object.keys(peoples[k]);
if (keys.length === 1) {
delete games[keys[0]][k];
delete peoples[k];
change = true;
return;
}
});
} while (change);
console.log(peoples);
console.log(games);

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