[英]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.