next.js 根据数组选择比较多个对象/数组,并输出一个包含所有匹配数组选择的对象

zi8p0yeb  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(133)

选择= [“A”,“lv3”,“大型”]

Data = [{ 
 id:1, title:"this is test 1", category:"A, D", level:"lv5", size: " 
 medium", }, 
 id:2, title:"this is test 1", category:"C", level:"lv1", size: "large", 
 },
 id:3, title:"this is test 1", category:"A, C", level:"lv3", size: " 
 medium, large", },
 id:4, title:"this is test 1", category:"B", level:"lv3, lv6", size: " 
 small", },
 id:5, title:"this is test 1", category:"B", level:"lv3", size: "large",
}]

以上为样本数据
输出应为一个“Data”对象,该对象仅包括在类别、级别和大小中找到的数组“selection”中的条目。
我已经尝试了下面的方法,但是一次只能处理一个对象

const [courseData, setCourseData] = useState(Data);
const [updatedCourseData, setUpdatedCourseData] = useState(courseData);

  const combleveleresult =
      Data &&
      Data.filter((data: any) => {
      const level = selection.includes(data.level.toLowerCase());
      return level;
  });

  const combcategoryeresult =
      Data &&
      Data.filter((data: any) => {
      const category = selection.includes(data.category.toLowerCase());
      return category ;
   });

   const combsizeeresult =
        Data &&
        Data.filter((data: any) => {
        const size= selection.includes(data.size.toLowerCase());
        return size;
    });

    setUpdatedCourseData(combleveleresult )

还尝试了以下操作,但问题相同,一次只能对对象起作用

const combine resultresult =
    courseData &&
    courseData.filter((data: any) => {
    const type = (data.type.toLowerCase().includes(selection) 
    || data.category.toLowerCase().includes(selection) || 
    data.level.toLowerCase().includes(selection));
    return type;
});

setUpdatedCourseData(resultresult)
8ftvxx2r

8ftvxx2r1#

const selection = ["A", "C", "lv3", "large"]

const data = [
{id:1, title:"this is test 1", category:"A, D", level:"lv5", size: "medium" },
{id:2, title:"this is test 2", category:"C", level:"lv1", size: "large" },
{id:3, title:"this is test 3", category:"A, C", level:"lv3", size: "medium, large" },
{id:4, title:"this is test 4", category:"B", level:"lv3, lv6", size: "small" },
{id:5, title:"this is test 5", category:"B", level:"lv3", size: "large"}]

console.log(data.filter(e=>selection.every(s=>
  ['category','level','size'].flatMap(j=>e[j].toLowerCase().split(', '))
    .includes(s.toLowerCase()))))

相关问题