有没有一种方法可以从包含特定值的对象中查找()随机元素

时间:2020-08-28 03:12:50

标签: javascript

我有一个包含健身房的物件,上面有可用的设备:

        const gyms = [
  {
    "name": "gym1",
    "equipmentAvailable": ["nothing"]
  },
  {
    "name": "gym2",
    "equipmentAvailable": ["jump rope","stationary bike","barbell"]
  },
  {
    "name": "gym3",
    "equipmentAvailable": ["kettlebell","dumbbell"]
  },
  {
    "name": "gym4",
    "equipmentAvailable": ["barbell","kettlebell","jump rope"]
  }
]

我还获得了下一个锻炼所需的设备清单(然后将其转换为Set):

const availableNeeded = ["barbell","jump rope"]

const equipmentSet = new Set(availableNeeded);

当前,我正在使用.find()拉出第一个符合我的设备需求的健身馆,

const filteredWorkouts = gyms.find(workout => (
  workout.equipmentAvailable.some(equipment => equipmentSet.has(equipment))
))

console.log(filteredWorkouts)

自然,这总是返回Gym2,因为它是第一个与所需设备匹配的健身房。 但是,有时我想将其切换到gym4,因为它具有所需的设备,但是find()无法提供。

我应该如何将Gym输出随机化,以便可以输出Gym2 Gym4?

1 个答案:

答案 0 :(得分:4)

使用.filter而不是.find来获取可能匹配的数组,然后从该数组中获取随机元素:

const gyms = [
  {
    "name": "gym1",
    "equipmentAvailable": ["nothing"]
  },
  {
    "name": "gym2",
    "equipmentAvailable": ["jump rope","stationary bike","barbell"]
  },
  {
    "name": "gym3",
    "equipmentAvailable": ["kettlebell","dumbbell"]
  },
  {
    "name": "gym4",
    "equipmentAvailable": ["barbell","kettlebell","jump rope"]
  }
];
const availableNeeded = ["barbell","jump rope"];
const filteredWorkouts = gyms.filter(gym => (
  availableNeeded.every(equip => gym.equipmentAvailable.includes(equip))
));
const result = filteredWorkouts[Math.floor(Math.random() * filteredWorkouts.length)];
console.log(result);