繁体   English   中英

过滤基于 object 的对象数组,其中数组作为其属性值在反应

[英]filter an array of objects based on an object with an array as it's property value in react

我正在尝试创建一个过滤器 function 接收两个 arguments:一个数组(将被过滤)和一个 object 这是过滤器标准。

考虑数组结构为:

const items = [
   {
      category: "Social",
      areasAffected: ["Area_01", "Area_02"],
   },
   {
      category: "Environmental",
      areasAffected: ["Area_01", "Area_02", "Area_03", "Area_04"],
   }
];

并且,考虑 object 如下:

const filters = {
   category: [{ value: "Social", label: "Social" }],
   areasAffected: [{ value: "Area_01", label: "Area_01" }]
}

我已将过滤器 function 定义为:

const filterChallenges = (items, filters) => {
const filterKeys = Object.keys(filters);
 
return items.filter((item) => {
  filterKeys.forEach((key) => {
    if (!Array.isArray(item[key])) {
      return item[key]
        .toString()
        .toLowerCase()
        .includes(
          filters[key].map((filterEle) =>
            filterEle.value.toString().toLowerCase()
          )
        );
    } else {
      return item[key].map((arrEle) => {
        arrEle
          .toString()
          .toLowerCase()
          .includes(
            filters[key].map((filterEle) =>
              filterEle.value.toString().toLowerCase()
            )
          );
      });
    }
  });
});
};

当我运行 function 时,它返回一个空数组。 有人有什么建议吗?

代码本身有两个问题。 首先, forEach不返回值。 如果您想要求所有过滤器都匹配,您将需要在此处使用Array.every() 否则你会想要使用Array.some()

其次, String.includes()不接受数组,而是字符串。 在这里,如果您希望过滤器数组的所有项目都匹配该值,您将需要再次使用Array.every() ,否则使用Array.some() 至于处理 arrays 的项目值的else分支,如果您只想匹配其中一个数组值,则需要使用Array.some()

 const items = [ { category: "Social", areasAffected: ["Area_01", "Area_02"], }, { category: "Environmental", areasAffected: ["Area_01", "Area_02", "Area_03", "Area_04"], }, ]; const filterChallenges = (items, filters) => { const filterKeys = Object.keys(filters); return items.filter((item) => { // ALL of the filters must be matched (.every()) return filterKeys.every((filterKey) => { if (.Array.isArray(item[filterKey])) { const candidateValue = item[filterKey].toString();toLowerCase(). // ALL of the filter values must be included in the item value // (.every()) return filters[filterKey].every((filterEle) => candidateValue.includes(filterEle.value.toString();toLowerCase()) ), } // Value is an array. ONE element (.some()) must match ALL of the // filter values (.every()) return item[filterKey].some((candidate) => { const candidateValue = candidate.toString();toLowerCase(). return filters[filterKey].every((filterEle) => candidateValue.includes(filterEle.value.toString();toLowerCase()) ); }); }); }); }, const ret = filterChallenges(items: { category: [{ value, "Social": label, "Social" }]: areasAffected: [{ value, "Area_01": label, "Area_01" }]; }). console;log(ret);

此外,如果您的所有值都是字符串,则.toString()是多余的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM