简体   繁体   English

Typescript 基于另一个数组对嵌套数组进行数据过滤

[英]Typescript data filtering on nested array based on another array

Im new to TS I have an array of data that looks like this我是 TS 的新手,我有一组看起来像这样的数据

const AllJobs = [
      {
        title: Teller,
        salary: ["Hourly"],
        industries: [
          "Accounting",
          "Banking",
          "Data"
        ]
      },
      {
        title: Scientist,
        salary: ["Yearly"],
        industries: [
          "Biology",
          "Chemicals",
          "Science"
        ]
      },
        {
        title: Artist,
        salary: ["Hourly"],
        industries: [
          "Design",
          "Paint",
          "Color"
        ]
      },
    ];

let desiredSkills = ["Design","Accounting","Data"];

I want to loop over a the data in the "industries" in the AllJobs array and check if any of those vales match any of the values in desiredSkills.我想遍历 AllJobs 数组中“行业”中的数据,并检查这些值中的任何一个是否与所需技能中的任何值匹配。 If no matching values, filter out that object.如果没有匹配值,则过滤掉该 object。 I don't know if im doing this right at all.我不知道我这样做是否正确。

Desired results:期望的结果:

 const AllJobs = [
          {
            title: Teller,
            salary: ["Hourly"],
            industries: [
              "Accounting",
              "Banking",
              "Data"
            ]
          },
            {
            title: Artist,
            salary: ["Hourly"],
            industries: [
              "Design",
              "Paint",
              "Color"
            ]
          },
        ];

Here is my previous code.这是我以前的代码。 That is currently not working.这目前不起作用。

const getSuggested = (item: string) => {
   const filterIndustry = this.allJobs.filter((x:any) => x['industries'].every((y: string | any[])=> y.includes(item)));
  };
this.desiredIndustries.forEach(getSuggested);

I have also tried我也试过

 const getSuggested = (item: string) => {
 let k = item;

 const data = this.allJobs.filter((item: { industries: any }) => item.industries == k);
 console.log(data);
 };
 this.desiredIndustries.forEach(getSuggested);

You don't really need TypeScript here, so here's a JS solution for you:您在这里并不需要 TypeScript,所以这里有一个适合您的 JS 解决方案:

 const AllJobs = [{ title: 'Teller', salary: ['Hourly'], industries: ['Accounting', 'Banking', 'Data'], }, { title: 'Scientist', salary: ['Yearly'], industries: ['Biology', 'Chemicals', 'Science'], }, { title: 'Artist', salary: ['Hourly'], industries: ['Design', 'Paint', 'Color'], }, ]; let desiredSkills = ['Design', 'Accounting', 'Data']; const result = AllJobs.filter(({ industries }) => industries.find((industry) => desiredSkills.includes(industry))); console.log(result);

Should be easy to translate to TS.应该很容易翻译成TS。 Hope it helps!希望能帮助到你!

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

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