我有一个JSON文件(https://api.myjson.com/bins/o7s1v),我想使用javascript来获取满足条件的随机对象,例如随机对象,其中" egg-group-1"等于"怪物"。
我将如何做到这一点?
答案 0 :(得分:-2)
如果要查找第一个匹配项,请使用find(),如果要查找随机项,可以使用filter()然后访问随机元素:
let arr = [{"id":1,"dex":1,"form":"null","mon":"Bulbasaur","type1":"Grass","type2":"Poison","egg-group-1":"Monster","egg-group-2":"Grass","legend":"FALSE","gen":1},{"id":2,"dex":2,"form":"null","mon":"Ivysaur","type1":"Grass","type2":"Poison","egg-group-1":"Monster","egg-group-2":"Grass","legend":"FALSE","gen":1}];
let first = arr.find(v => v['egg-group-1'] === 'Monster'); // will return the first one
console.log(first);
let random = arr.filter(v => v['egg-group-1'] === 'Monster');
console.log(random[Math.floor(Math.random()*random.length)]);