使用变量查找json对象



我正在尝试使用一个变量来匹配数组中的id

播放器下面有10个数组,我想循环浏览所有数组,看看我的变量是否与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(); 

所以它应该循环每个matchlist.players[0 to 9].id,看看它是否与我的userid变量匹配。

考虑这个例子:

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从数组中筛选出要查找的值。

简短回答:控制台,因为您无法从promise函数返回(除非使用then(

console.log(matchList.players.filter(player => player.id === userid)[0])

长答案:如果您在控制台中执行此代码,它将控制台信息:

1-西班牙

2-Elsa

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);

如果你需要任何解释,或者这不是你所问的,请评论我的回答

这应该可以做到:

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)
}

最新更新