[英]Use variable to find json object
我正在尝试使用变量来匹配数组中的 id
玩家下有 10 个 arrays ,我想循环浏览所有这些以查看我的变量是否与 id 匹配。 如果是这样,它应该使用该数组来显示对象。
async function showMatch() {
// My variable
let userid = 71471603
let Response = await fetch(`https://api.myjson.com/bins/1e96uo`);
let matchlist = await Response.json();
}
showMatch();
所以它应该 go 循环每个matchlist.players[0 to 9].id
,看看它是否与我的用户 ID 变量匹配。
考虑这个例子:
const animals = [
{
"name": "cat",
"size": "small",
"weight": 5
},
{
"name": "dog",
"size": "small",
"weight": 10
},
{
"name": "lion",
"size": "medium",
"weight": 150
},
{
"name": "elephant",
"size": "big",
"weight": 5000
}
];
let filterArray = animals.filter((animal) => {return animal.size === 'small'});
console.log(filterArray);// Returns an array which satisfies the match
使用.filter
从数组中过滤掉要查找的值。
这应该可以解决问题:
async function showMatch() {
const userid = 71471603
const Response = await fetch(`https://api.myjson.com/bins/1e96uo`);
const matchlist = await Response.json();
return matchlist.players.filter(player => players.id === userid)
}
简短回答:控制台,因为您无法从 promise function 返回(使用 then 除外)
console.log(matchList.players.filter(player => player.id === userid)[0])
长答案:如果您在控制台中执行此代码,它将控制以下信息:
1-西班牙人
2-艾尔莎
async function showMatch(idOfSpecificUser) {
// idOfSpecificUser: the id of the user you want his/her information
// make the GET request
let response = await fetch(`https://api.myjson.com/bins/1e96uo`);
// convert the response to JSON
let responseToJson = await response.json();
// take the players array from the response after convert it to JSON
let playersArrayOfObject = responseToJson.players;
// console.log(playersArrayOfObject); // => [ {}, {}, {}, ... ]
// now the real fun start
// you need to iterate over this array and get the user data
// why [0] cause filter return to you array of object (we need the first match)
// or the only one match // => [ {id: 71471603, username: "EspartaN", .....} ]
let userInfo = playersArrayOfObject.filter(
user => user.id === idOfSpecificUser
)[0];
console.log(userInfo.username); //=> "EspartaN"
console.log(userInfo); // => { id: 71471603, username: "EspartaN", ..... }
}
// => "EspartaN"
showMatch(71471603);
// => "Elsa"
showMatch(97531);
如果您需要任何解释,或者这不是您要问的,请评论我的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.