如何在Javascript中过滤对象数组

时间:2018-06-12 23:07:07

标签: javascript html arrays filter

我正在尝试在Javascript中创建一个函数,这将允许我过滤不同候选人所拥有的技能,我被告知这可以在Javascript中完成,名为“filterCandidateBySkill”的函数是我想要的地方过滤候选技能,但我已经看过这个,因为技能是在一个阵列,我无法在网上找到如何过滤它。他们中的很多人都有单个单词的过滤器,但不适用于数组。

const newCandidates = [
  { name: "bob", skills: ["JavaScript", "Docker", "Ruby"] },
  { name: "ally", skills: ["Python", "AWS"] },
  { name: "joe", skills: ["JavaScript", "Azure"] },
  { name: "fred", skills: ["JavaScript", "Java"]},
];

function filterCandidateBySkill(candidates, skill) {
  // where im confused
}

1 个答案:

答案 0 :(得分:7)

JS在数组上提供了一个过滤方法。

const newCandidates = [
  { name: "bob", skills: ["JavaScript", "Docker", "Ruby"] },
  { name: "ally", skills: ["Python", "AWS"] },
  { name: "joe", skills: ["JavaScript", "Azure"] },
  { name: "fred", skills: ["JavaScript", "Java"]},
];

function filterCandidateBySkill(candidates, skill) {
  return newCandidates.filter(candidate => candidate.skills.includes(skill));
}

// Get only names
console.log(filterCandidateBySkill(newCandidates, 'JavaScript').map(candidate => candidate.name));

// Get entire objects
console.log(filterCandidateBySkill(newCandidates, 'JavaScript'));