如何从过滤器的过滤器返回值?

时间:2019-11-19 05:28:43

标签: javascript typescript ecmascript-6

我想让所有以数学为主题的学生

var student = [{
  name: 'XYZ',
  age: 15,
  subject: ['Maths', 'Science'],
}, {
  name: 'XYZ',
  age: 15,
  subject: ['Hindi', 'Science'],
}, {
  name: 'XYZ',
  age: 15,
  subject: ['Maths', 'English'],
}];

我已经尝试过了,但是不起作用:

student.filter(x=>x.subject.filter(y=>y=='Maths'));

任何帮助将不胜感激

8 个答案:

答案 0 :(得分:3)

您需要组合filter()some()来检查是否有主题Maths

var student = [{
    name: 'XYZ',
    age: 15,
    subject: ['Maths', 'Science'],
  },
  {
    name: 'XYZ',
    age: 15,
    subject: ['Hindi', 'Science'],
  },
  {
    name: 'XYZ',
    age: 15,
    subject: ['Maths', 'English'],
  }
];

console.log(student.filter(x => x.subject.some(y => y == 'Maths')));

答案 1 :(得分:1)

尝试这样

student.filter(x=>x.subject.indexOf('Maths')!=-1);

答案 2 :(得分:1)

student.filter(x => x.subject.some(y => y == 'Maths')

答案 3 :(得分:1)

您只需在includes内使用filter

 var student=[
    {
      name:'XYZ',
      age:15,
      subject:['Maths','Science'],
    },
    {
      name:'XYZ',
      age:15,
      subject:['Hindi','Science'],
    },
    {
      name:'XYZ',
      age:15,
      subject:['Maths','English'],
    }
   ]
 student=student.filter(x=>x['subject'].includes('Maths'));
 console.log(student);
 

答案 4 :(得分:1)

您很近。要搜索数组中的第一个匹配项,请使用indexOf函数。

这将返回可以在数组中找到给定元素的第一个索引;如果不存在,则返回-1。

因此,我们需要检查结果是否为> -1 ,以表明我们有匹配项。

查看摘要:

var student = [{
    name: 'XYZ',
    age: 15,
    subject: ['Maths', 'Science']
  },
  {
    name: 'XYZ',
    age: 15,
    subject: ['Hindi', 'Science']
  },
  {
    name: 'XYZ',
    age: 15,
    subject: ['Maths', 'English']
  }
];

console.log(student.filter(x => x.subject.indexOf('Maths') > -1));

答案 5 :(得分:1)

您可以在打字稿中使用include()方法

var student = [{
    name: 'XYZ',
    age: 15,
    subject: ['Maths', 'Science'],
  },
  {
    name: 'XYZ',
    age: 15,
    subject: ['Hindi', 'Science'],
  },
  {
    name: 'XYZ',
    age: 15,
    subject: ['Maths', 'English'],
  }
];

console.log(student.filter(x => x.subject.includes('Maths')));

答案 6 :(得分:1)

这已经得到了更详细的回答:-

https://stackoverflow.com/a/38375768/7562674

根据您的情况:-

  var st=student.filter((stud) => 
  stud.subject.some((subElement) => subElement === "Maths")
 );
  console.log(st)

答案 7 :(得分:1)

var student = [{
  name: 'XYZ',
  age: 15,
  subject: ['Maths', 'Science'],
}, {
  name: 'XYZ',
  age: 15,
  subject: ['Hindi', 'Science'],
}, {
  name: 'XYZ',
  age: 15,
  subject: ['Maths', 'English'],
}];

let findResult = (subject) => student.filter(o => o.subject.find( i => i == subject ));
let result = findResult('Maths');
console.log(result);

  

您可以使用filter methodfind method返回值   提供的数组中满足提供条件的第一个元素的元素   测试功能。