需求:实现按指定兴趣筛选人员的JavaScript函数
嘿,我来帮你搞定这个查找兴趣对应人员的问题!
问题分析
首先得提个小坑:你原来的对象和函数都叫people,这会导致变量名冲突——函数会直接覆盖掉之前的人员对象,所以第一步得给函数换个名字,比如findPeopleByInterest,避免踩坑。
咱们的核心需求很明确:给定一个存储人员与对应兴趣的对象,传入某个兴趣名称,返回所有拥有该兴趣的人员名字数组。
解决方案
这里给你两种实现方式,你可以根据自己的习惯选择:
方式一:ES6链式调用(简洁优雅)
// 先定义好人员对象 const people = {'Steven': ['football', 'hockey'], 'Maria': ['writing', 'swimming']}; // 定义查找函数 function findPeopleByInterest(peopleObj, interest) { // 把对象转成键值对数组,过滤出包含目标兴趣的项,再提取名字 return Object.entries(peopleObj) .filter(([name, interests]) => interests.includes(interest)) .map(([name]) => name); } // 测试看看效果 console.log(findPeopleByInterest(people, 'swimming')); // 输出: ['Maria'] console.log(findPeopleByInterest(people, 'hockey')); // 输出: ['Steven']
代码拆解:
Object.entries(peopleObj):把人员对象转换成[['名字', ['兴趣1', '兴趣2']], ...]这样的键值对数组,方便后续遍历处理.filter(...):筛选出那些兴趣数组里包含目标兴趣的键值对.map(...):把筛选后的结果只提取出人员名字,组成最终要返回的数组
方式二:普通循环写法(新手友好)
如果你觉得链式调用有点绕,用传统的循环逻辑也能轻松实现:
const people = {'Steven': ['football', 'hockey'], 'Maria': ['writing', 'swimming']}; function findPeopleByInterest(peopleObj, interest) { const matchedPeople = []; // 遍历对象里的每一个人员名字 for (const name in peopleObj) { // 检查当前人员的兴趣列表是否包含目标兴趣 if (peopleObj[name].includes(interest)) { matchedPeople.push(name); } } return matchedPeople; }
额外优化:忽略大小写匹配
如果需要支持不区分兴趣的大小写(比如传入Swimming也能匹配到swimming),可以修改判断逻辑:
function findPeopleByInterest(peopleObj, interest) { const lowerCaseInterest = interest.toLowerCase(); return Object.entries(peopleObj) .filter(([name, interests]) => interests.some(i => i.toLowerCase() === lowerCaseInterest) ) .map(([name]) => name); }
内容的提问来源于stack exchange,提问作者user9399141
相关产品推荐
相关产品推荐

