简体   繁体   English

从 Javascript 中嵌套数组内的对象中过滤数据的最佳方法

[英]Best way to filter data from objects inside nested array in Javascript

Given the below data, how can I filter data by Framework and return Name and Project?给定以下数据,如何按框架过滤数据并返回名称和项目? I am trying to set up a search box that would call the filter function.我正在尝试设置一个搜索框来调用过滤器 function。

I can do it if the data is in an array, but not sure how to work in this nested array and object scenario.如果数据在数组中,我可以这样做,但不确定如何在这个嵌套数组和 object 场景中工作。

const data = [

  { 

     name: 'John Doe', 
     projects: [ 
                 { ProjectName: 'something', Framework: 'React' },
                 { ProjectName: 'something', Framework: 'React Native' },
                 { ProjectName: 'something', Framework: 'NextJS' },
               ]
  },
  { 

     name: 'Jane Doe', 
     projects: [ 
                 { ProjectName: 'something', Framework: 'Vanilla Javascript' },
                 { ProjectName: 'something', Framework: 'Angular' },
                 { ProjectName: 'something', Framework: 'Flutter' },
               ]
  }


]

I can filter by Name using this:我可以使用这个按名称过滤:

const filteredData = data.filter((item) => {
    return item.name.toLowerCase().includes(searchField.toLowerCase());
  });

But I am not sure how to filter by project name or framework.但我不确定如何按项目名称或框架进行过滤。

Inside your filter, you can use the some what is gonna return true if the condition is met at least once Example: you will be able to have every user with the given project Name在您的过滤器中,您可以使用一些如果条件至少满足一次将返回 true 示例:您将能够让每个用户都具有给定的项目名称

let filteredData = data.filter(i => i.projects.some(p => p.ProjectName === 'something'))

If you are looking for a filtered objects inside, it means, removing the useless projects without the right projectname name you can add a map on your filtered data如果您正在寻找内部过滤的对象,这意味着,删除没有正确项目名称的无用项目,您可以在过滤的数据上添加 map

filteredData.map(i => { 
   i.projects = i.projects.filter(p => p.ProjectName === 'something');
   return i;
})

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

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