首页 > 解决方案 > 查找方法不返回'0th'匹配的对象反应,或反应本机或javascript

问题描述

没有得到所有匹配的对象,它返回除了'{ ID:0,名称:'General Group'}'之外的所有对象,我想要所有匹配的对象

 let arrDashboardIconGroups = [
      { ID:0, Name: 'General Group' },
      { ID: 1, Name: 'Patient Administration' },     
      { ID: 2, Name: 'Medical Charts' },
      { ID: 3, Name: 'Medical Procedures' },
      { ID: 13, Name: 'Purchase' },
      { ID: 14, Name: 'Sales' },
      { ID: 5, Name: 'Insurance' },
      { ID: 4, Name: 'Cash' },
      { ID: 6, Name: 'Pharmacy' },
      { ID: 7, Name: 'Inventory' },
      { ID: 8, Name: 'Lab' },
      { ID: 9, Name: 'Imaging' },
      { ID: 10, Name: 'In Patient' },
      { ID: 11, Name: 'System Administration' },
      { ID: 12, Name: 'Accounting' }
  ]  

const getMatchedobjects=()=> {

   let result = [0,1,2,3,4,]
   let matchedArray = arrDashboardIconGroups.filter(val =>result.find(
      (items)=>items == val.ID))

   console.log(matchedArray)
}

getMatchedobjects()

标签: javascriptreactjsreact-native

解决方案


您正在返回的值

result.find((items) => items == val.ID)

在第一种情况下,返回的值0是一个falsy值。所以它不会包含在最终的过滤结果中。

您可以运行以下代码并查看返回值。

let arrDashboardIconGroups = [
  { ID: 0, Name: "General Group" },
  { ID: 1, Name: "Patient Administration" },
  { ID: 2, Name: "Medical Charts" },
  { ID: 3, Name: "Medical Procedures" },
  { ID: 13, Name: "Purchase" },
  { ID: 14, Name: "Sales" },
  { ID: 5, Name: "Insurance" },
  { ID: 4, Name: "Cash" },
  { ID: 6, Name: "Pharmacy" },
  { ID: 7, Name: "Inventory" },
  { ID: 8, Name: "Lab" },
  { ID: 9, Name: "Imaging" },
  { ID: 10, Name: "In Patient" },
  { ID: 11, Name: "System Administration" },
  { ID: 12, Name: "Accounting" },
];

const getMatchedobjects = () => {
  let result = [0, 1, 2, 3, 4];
  let matchedArray = arrDashboardIconGroups.filter((val) => {
    const returnResult = result.find((items) => items == val.ID);
    console.log(returnResult);
    return returnResult;
    // result.includes(val.ID)
  });

  console.log(matchedArray);
};

getMatchedobjects();

或者,您可以使用包含

let arrDashboardIconGroups = [
  { ID: 0, Name: "General Group" },
  { ID: 1, Name: "Patient Administration" },
  { ID: 2, Name: "Medical Charts" },
  { ID: 3, Name: "Medical Procedures" },
  { ID: 13, Name: "Purchase" },
  { ID: 14, Name: "Sales" },
  { ID: 5, Name: "Insurance" },
  { ID: 4, Name: "Cash" },
  { ID: 6, Name: "Pharmacy" },
  { ID: 7, Name: "Inventory" },
  { ID: 8, Name: "Lab" },
  { ID: 9, Name: "Imaging" },
  { ID: 10, Name: "In Patient" },
  { ID: 11, Name: "System Administration" },
  { ID: 12, Name: "Accounting" },
];

const getMatchedobjects = () => {
  let result = [0, 1, 2, 3, 4];
  let matchedArray = arrDashboardIconGroups.filter((val) => result.includes(val.ID));

  console.log(matchedArray);
};

getMatchedobjects();


推荐阅读