首页 > 解决方案 > 使用变量查找 json 对象

问题描述

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

player 下有 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(); 

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

标签: javascriptarraysjsonfetch

解决方案


考虑这个例子:

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从数组中过滤掉您要查找的值。


推荐阅读