Javascript - 循环嵌套数组和对象过滤器

时间:2021-02-19 00:16:24

标签: javascript arrays sorting

尝试使用特定的想法获取所有数组。不知道如何在那里执行过滤,但我想我会在这里问。希望我想要做的事情已经足够清楚了。我几乎有一个课程列表,并希望获得 level = 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); 

2 个答案:

答案 0 :(得分:1)

您可能想做一些类似的事情:

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));

答案 1 :(得分:0)

您可以按条目的 level_id(值内)过滤条目,然后映射其课程名称(键)。

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

注意:由于您的对象嵌套在一个数组中,您可以销毁该对象,然后将其转换为条目。

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; }