在使用Fetch API对端点进行提取后,我的响应包含一个包含2个数组的对象,看起来像这样。
{games_list: Array(192), owner_list: Array(4)}
在每个数组中都有一个唯一的标识符,两个数组共享例如 node_id
我需要一种方法来检索一个独特的所有者拥有的所有游戏,最后我将列出4个所有者的列表以及每个所有者拥有的游戏数量(希望这是有道理的)
到目前为止,我得到的是以下内容:
const getData = () => {
fetch('./data.json')
.then(res => res.json())
.then(data => {
console.log(data) // all data
const allGames = data.games_list
const allOwners = data.owner_list
// Get all id's for games_list and owner_list
const gameNodeIds = allGames.map(id => id.node_id)
const ownerNodeIds = allOwners.map(id => id.node_id)
})
.catch(err => console.error(`Error: ${err}`))
}
返回的数据示例:
{
"games_list": [
{
"game": "Overwatch",
"game_type": "Shooter",
"developers": "Blizzard",
"node_id": "123456778"
}
],
.....
"owners_list": [
{
"name": "John Doe",
"age": "25",
"Occupation": "gamer",
"node_id": "123456778"
}
]
}
据我所知,我真的需要一些帮助从这里前进,所以所有的帮助将不胜感激。
答案 0 :(得分:2)
您可以合并map()
和filter()
以使所需结构返回所需结果
请参阅代码段
var data = {
"games_list": [
{
"game": "game1",
"game_type": "Shooter",
"developers": "Blizzard",
"node_id": "1"
},
{
"game": "game2",
"game_type": "Shooter",
"developers": "Blizzard",
"node_id": "1"
},
{
"game": "game3",
"game_type": "Shooter",
"developers": "Blizzard",
"node_id": "2"
}
],
"owners_list": [
{
"name": "owner 1",
"age": "25",
"Occupation": "gamer",
"node_id": "1"
},
{
"name": "owner 2",
"age": "25",
"Occupation": "gamer",
"node_id": "2"
},
{
"name": "owner 3",
"age": "25",
"Occupation": "gamer",
"node_id": "3"
}
]
}
const allGames = data.games_list;
const allOwners = data.owners_list;
var result = allOwners.map(owner =>
({owner: owner.name,
games:allGames.filter(game => game.node_id === owner.node_id
).length
})
)
console.log(result);

答案 1 :(得分:0)
所以你必须找到你的特定node_id在allGames中存在多少次?
var games_by_owner = {};
allOwners.forEach(function(ele, idx){
gameNoeIds.forEach(function(eleG, idxG){
if(typeof games_by_owner[idx] == 'undefined') {
games_by_owner[idx] = [];
}
if (ele.node_id == eleG.node_id) {
games_by_owner[idx].push(idxG);
}
});
});
因此,您将收集其游戏idxG的每个所有者idx数组。
答案 2 :(得分:0)
使用对象或Map以及公共键值作为属性来创建counts
对象
以下假设某些游戏可能没有所有者列表中的所有者,而您只想要现有所有者的计数
let data = {
"games_list": [
{
"game": "Overwatch",
"game_type": "Shooter",
"developers": "Blizzard",
"node_id": "123456778"
}
],
"owners_list": [
{
"name": "John Doe",
"age": "25",
"Occupation": "gamer",
"node_id": "123456778"
}
]
}
let ownerCounts = data.owners_list.reduce((a,c)=> (a[c.node_id]=0,a),{});
data.games_list.forEach(g=> g.node_id in ownerCounts && ownerCounts[g.node_id]++);
console.log(ownerCounts)
如果不担心游戏所有者在游戏所有者列表中,您只需要循环游戏列表
let data = {
"games_list": [
{
"game": "Overwatch",
"game_type": "Shooter",
"developers": "Blizzard",
"node_id": "123456778"
}
],
"owners_list": [
{
"name": "John Doe",
"age": "25",
"Occupation": "gamer",
"node_id": "123456778"
}
]
}
let ownerCounts = data.games_list.reduce((a,c)=> (a[c.node_id]= (a[c.node_id]||0)+1,a),{});
console.log(ownerCounts)