繁体   English   中英

Javascript - 循环通过嵌套的 arrays 和对象过滤器

[英]Javascript - Loop through nested arrays and objects filter

尝试使用特定的想法获取所有 arrays。 不知道如何在那里执行过滤,但我想我会在这里问。 希望它足够清楚我正在尝试做什么。 几乎我有一个课程列表,并希望获得所有级别 = 1 的课程。

 let courses = [{
               math:[{id:1,level_id:1,requirement:'1 Credit'}]
               spanish:[{id:5,level_id:1,requirement:'5 Credits'}] 
               technology:[{id:3,level_id:1,requirement:'2 Credits'}]
            }];
             
            let queryCoursesForLevelWhereIDMatches = 1
            
            let returnedArrays = courses.filter()
             
             console.log(returnedArrays); 

您可能想要按照以下方式做一些事情:

 function CourseMaster(courses = null){ this.courses = courses; this.getMath = (byProp, byVal = null)=>{ return this.courses.math.filter(o=>{ let p = o.hasOwnProperty(byProp); if(byVal === null){ return p; } return p && byVal === o[byProp]; }); } this.getSpanish = (byProp, byVal = null)=>{ return this.courses.spanish.filter(o=>{ let p = o.hasOwnProperty(byProp); if(byVal === null){ return p; } return p && byVal === o[byProp]; }); } this.getTech = (byProp, byVal = null)=>{ return this.courses.technology.filter(o=>{ let p = o.hasOwnProperty(byProp); if(byVal === null){ return p; } return p && byVal === o[byProp]; }); } this.getAll = (byProp, byVal = null)=>{ const m = this.getMath(byProp, byVal), s = this.getSpanish(byProp, byVal), t = this.getTech(byProp, byVal); return {math:m, spanish:s, technology:t} } } const courses = { math:[{id:1,level_id:1,requirement:'1 Credit'}, {id:2,level_id:2,requirement:'2 Credits'}], spanish:[{id:2,level_id:2,requirement:'2 Credits'}, {id:5,level_id:1,requirement:'5 Credits'}], technology:[{id:3,level_id:1,requirement:'2 Credits'}, {id:2,level_id:2,requirement:'2 Credits'}] } const cm = new CourseMaster(courses); console.log(cm.getAll('level_id', 1));

您可以按它们的level_id (在值内)过滤条目,然后按 map 他们的课程名称(键)。

此外,我将“西班牙语”更改为第 2 级,以确保它不会返回。

注意:由于您的 object 嵌套在数组中,您可以破坏 object 然后将其转换为条目。

 let courses = [{ math: [ { id: 1, level_id: 1, requirement: '1 Credit' } ], spanish: [ { id: 5, level_id: 2, requirement: '5 Credits' } ], technology: [ { id: 3, level_id: 1, requirement: '2 Credits' } ] }]; const findCoursesWhereLevelIdEquals = ([ courses ], id) => Object.entries(courses).filter(([, [ { level_id } ] ]) => level_id === id).map(([ courseName ]) => courseName); console.log(findCoursesWhereLevelIdEquals(courses, 1));
 .as-console-wrapper { top: 0; max-height: 100%;important; }

暂无
暂无

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

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