根据多个属性过滤js对象数组

问题描述 投票:0回答:1

(使用react js)我正在尝试过滤这个数组:

[
  {gov:"A1", district:"1" , town:"t1", type:"cars factory"},
  {gov:"A2", district:"2" , town:"t2", type:"farm"},
  {gov:"A1", district:"1" , town:"t1", type:"milk factory"},
  {gov:"A1", district:"4" , town:"t3", type:"milk factory"},
  {gov:"A3", district:"3" , town:"t4", type:"medicine factory"},
  {gov:"A4", district:"6" , town:"t5", type:"food"},
  {gov:"A3", district:"7" , town:"t4", type:"milk factory"},
  {gov:"A2", district:"2" , town:"t7", type:"construction"},
]

假设这个数组称为 Locations,我需要实现 4 个过滤器,第一个过滤器是使用 gov(省份)过滤,第二个过滤器是使用 Districts ,第三个过滤器使用城镇,最后使用工业类型。 但是,如果我已经选择了按地区过滤,那么我想过滤该地区内的行业类型,我需要动态地进行;这样,我实现了 4 个选择输入(政府、区、城镇、类型),我本来可以始终过滤原始数组,但这将始终返回所有政府中的牛奶工厂,而不是特定的政府。 所以我需要的是根据多个属性或属性进行过滤,而不是仅仅静态地编写它

newArray=Locations.filter( (e)=>{ return e.gov=='A1' && e.type='milk factory'}) 

这可以解决问题,但并非总是如此,因为我也可能选择过滤特定地区、城镇甚至整个国家(在父数组上)的牛奶工厂

我们假设

gov \\is the value of the selection of governorates
district \\is the value of the selection of districts
town \\is the value of the selection of towns
type \\is the value of the selection of the type

顺便说一句,我正在使用反应传单地图在标记上显示这些值,这就是我需要过滤的原因。

所以我想把它发布在这里,也许善良的灵魂会帮助我解决这个问题 谢谢大家

javascript arrays reactjs search filtering
1个回答
4
投票

您可以使用以下方法。这个想法是将所有过滤器放在一个匹配对象中,然后在每次更改

filterData
 时调用 
matchObj

const data = [
  {gov:"A1", district:"1" , town:"t1", type:"cars factory"},
  {gov:"A2", district:"2" , town:"t2", type:"farm"},
  {gov:"A1", district:"1" , town:"t1", type:"milk factory"},
  {gov:"A1", district:"4" , town:"t3", type:"milk factory"},
  {gov:"A3", district:"3" , town:"t4", type:"medicine factory"},
  {gov:"A4", district:"6" , town:"t5", type:"food"},
  {gov:"A3", district:"7" , town:"t4", type:"milk factory"},
  {gov:"A2", district:"2" , town:"t7", type:"construction"},
];

const filterData = (matchObj) => {
  const matchEntries = Object.entries(matchObj);
  return data.filter(item => {
    return matchEntries.every(([key, val]) => item[key] === val);
  });
};


// Tests:
const matchObj1 = { gov:"A1" };
console.log(matchObj1, filterData(matchObj1));

const matchObj2 = { gov:"A1", type: "milk factory" };
console.log(matchObj2, filterData(matchObj2));

const matchObj3 = { gov:"A1", type: "milk factory", town: "t3" };
console.log(matchObj3, filterData(matchObj3));
  

© www.soinside.com 2019 - 2024. All rights reserved.