如何在Java脚本中过滤数组中的多个值

2022-06-29 00:00:00 arrays filtering javascript

我有一个json元素数组。我想根据特定值过滤数组。下面是数组。

var arr = [
{name: bobby, id: 1, age: 23},
{name: charls, id: 2, age: 28},
{name: indi, id: 3, age: 23},
{name: charlie, id: 4, age: 25}]
从上面的数组中,我想只过滤名字是Bobby&;&;indi的员工。我尝试过以下代码。

var filteredArray;
for (var i =0 ; i < arr.length; i++){
    if(arr[i].name === 'bobby' || arr[i].name === 'indi'){
        filteredArray.push(arr[i]);
    }
}
但通过上面的代码,我需要多次提到OR(||)条件,这些名称的数量可能会发生变化,比如1次我只想要有Bobby名字的员工,而其他时间我想要Bobby、Indi和Charlie。有没有办法让它充满活力。如果是的话,请告诉我。提前谢谢。


解决方案

您可以将需要筛选的名称存储在数组中,然后检查名称是否存在于数组中

例如

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
var arr = [
    {name: "bobby", id: 1, age: 23},
    {name: "charls", id: 2, age: 28},
    {name: "indi", id: 3, age: 23},
    {name: "charlie", id: 4, age: 25}
]
const names = ["bobby", "indi"];

const filtered = arr.filter((item)=>{
  return names.includes(item.name)
});

console.log(filtered)

对于较老的(例如IE11)浏览器-

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
var arr = [
    {name: "bobby", id: 1, age: 23},
    {name: "charls", id: 2, age: 28},
    {name: "indi", id: 3, age: 23},
    {name: "charlie", id: 4, age: 25}
]
const names = ["bobby", "indi"];

const filtered = [];

for(var i =0; i<arr.length - 1; i++){
  if(names.indexOf(arr[i].name) > -1){
      filtered.push(arr[i])
  }
}

console.log(filtered)

相关文章