使用javascript检查forEach响应中所有条件的更有效方法

使用javascript检查forEach响应中所有条件的更有效方法,javascript,if-statement,foreach,react-hooks,Javascript,If Statement,Foreach,React Hooks,我有一个发送选项的值(如下所列)。然后将该值传递到React钩子。这是可行的,但是有没有更干练/更干净/更有效的方法来处理条件语句 选择选项 const animals = [ "Cows", "Pigs", "Sheep", "Goats", "Lambs", "Rabbits" ] 功能 const _updateLocationData = (value) => { var tempLocations = []; locations.forEach(funct

我有一个
发送
选项的值(如下所列)。然后将该值传递到React钩子。这是可行的,但是有没有更干练/更干净/更有效的方法来处理条件语句

选择选项

const animals = [
  "Cows", "Pigs", "Sheep", "Goats", "Lambs", "Rabbits"
]
功能

const _updateLocationData = (value) => { 
    var tempLocations = [];
    locations.forEach(function(res) {
        if (value === "Cows" && res.Cows === "Yes") {
            tempLocations.push(res);
        }
        if (value === "Pigs" && res.Pigs === "Yes") {
            tempLocations.push(res);
        }
        if (value === "Sheep" && res.Sheep === "Yes") {
            tempLocations.push(res);
        }
        if (value === "Goats" && res.Goat === "Yes") {
            tempLocations.push(res);
        }
        if (value === "Lambs" && res.Lamb === "Yes") {
            tempLocations.push(res);
        }
        if (value === "Rabbits" && res.Rabbit === "Yes") {
            tempLocations.push(res);
        }
    });
}

考虑这样的情况:只需确认
在所需数组中,然后检查
res
[value]
属性是否等于
“Yes”


您可以使用
filter
方法筛选出数组

const动物=[
“牛”、“猪”、“羊”、“山羊”、“羊羔”、“兔子”
];
让位置=[
{奶牛:“是的,},
{猪:'是',},
{绵羊:'是',},
{山羊:'是',},
{羔羊:'是',},
{兔子:'是',},
];
常量updateLocationData=(值)=>{
var tempLocations=locations.filter(res=>(animals.includes(value)&&res[value]==='Yes');
console.log(模板定位);
}
_更新定位数据(“奶牛”);
_更新定位数据(“猪”);
_updateLocationData(“绵羊”);
_updateLocationData(“山羊”)如何使用:if(anives.indexOf(value)>-1&&res[value]=='Yes'){templations.push(res);}
const animals = [
  "Cows", "Pigs", "Sheep", "Goats", "Lambs", "Rabbits"
]

const _updateLocationData = (value) => { 
    var tempLocations = [];
    locations.forEach(function(res) {
        if (animals.includes(value) && res[value] === "Yes") {
            tempLocations.push(res);
        }
    });
}