Javascript - Iterating through nested arrays and objects to apply filtering

I am currently trying to fetch specific arrays based on a certain criterion. I am a bit unsure about how to go about filtering the arrays, so I thought I would seek clarification here. Essentially, I have a list of courses and I want to extract all the courses where the level is equal to 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); 

Answer №1

If you're looking to implement a solution, consider the following approach:

function CourseManager(courses = null){
  this.courses = courses;
  this.getByCategory = (category, value = null)=>{
    return this.courses[category].filter(course=>{
      let propertyExists = course.hasOwnProperty(value);
      if(value === null){
        return propertyExists;
      }
      return propertyExists && value === course[value];
    });
  }
  this.getAllCourses = (category, value = null)=>{
    const mathCourses = this.getByCategory('math', value);
    const spanishCourses = this.getByCategory('spanish', value);
    const techCourses = this.getByCategory('technology', value);
    return {math: mathCourses, spanish: spanishCourses, technology: techCourses}
  }
}
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 CourseManager(courses);
console.log(cm.getAllCourses('level_id', 1));

Answer №2

You have the ability to filter the entries based on their level_id values and then associate them with their respective course names.

Furthermore, I have reassigned "Spanish" to level 2 to ensure it is excluded from the results.

Important: As the object is nested within an array, you can destructure the object and then transform it into individual entries.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to adjust offset/repeat of texture being utilized as alphaMap

demo: the alphaTexture is being modified in its offset with each render. When used as a "map" property, the offset changes, but when used as an "alphaMap" it remains static. This issue arises with the second mesh's alphaMap. relevant code from demo ...

Instructions on transferring every element of a json object into a two-dimensional array, specifically when the object title corresponds (ArduinoJson)

Currently, I'm undertaking an Arduino project that involves mixing cocktails automatically. To achieve this, I've opted to store a collection of cocktail recipes in a JSON file called cocktails.json, located on an SD card. When a cocktail is sele ...

How to delete an element from an array with UnderscoreJS

Here's a scenario: var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]; I'm looking to delete the element with id value of 3 from this array. Is there a method to achieve this without using splice? Perhap ...

Error message encountered in Express.js when trying to apply the ejs function: "View is not a constructor"

I am attempting to execute certain tasks before the original app.get function is called. After referring to this page, I applied their method which worked for the most part, except when using a rendering engine. The code snippet below demonstrates what I ...

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

AdminLTE-3 Bootstrap-4 sidebar menu with dynamic AJAX functionality fails to toggle treeview open/hide after page is fully loaded

I am looking to update the sidebar menu dynamically in the adminlte 3 dashboard with bootstrap 4 using AJAX calls. However, I have run into an issue where the menu open/close functionality is not working when the data is loaded dynamically using AJAX. On t ...

Retrieving detailed information from MongoDB in a Node.js environment

I am currently developing a nodejs server using mongoDB. I have some sample data that looks like this: { "_id": ObjectId("555f1c0c7f4b820758b439b0"), "user": "Guest1", "friend": [{ "myfriend": "Guest2", "in ...

Error: Attempting to access property 'baseHref' of an undefined value is not possible

Creating a webpack configuration for Angular 7 has been my recent project. I found a helpful tutorial on how to customize build configuration at this link. I decided to use the @angular-builders package for this task. Upon checking my index.html file, I m ...

Is there a way to eliminate the repeated query in the MySQL/PHP output array and only display the result once?

I'm trying to run a query that checks if a specific value exists in my table and then stores the result in an array, outputting it as JSON. However, my response always includes unnecessary data like {"SELECT EXISTS(SELECT * FROM wp_woocommerce_order_i ...

How can I convert duplicate code into a function in JavaScript?

I have successfully bound values to a view in my code, but I am concerned about the duplicate nested forEach loops that are currently present. I anticipate that Sonarcube will flag this as redundant code. Can anyone advise me on how to refactor this to avo ...

Unable to retrieve data on the frontend using Node.js and React

I have been attempting to retrieve all user data from the backend to display on the webpage. However, it seems that the getAllUsers() function is not returning a response, as no console logs are being displayed. Here is my ViewUsers.js file: import React, ...

What level of detail is optimal for my model?

What is the best approach for structuring data models in Meteor? For example, let's consider a data model with a XmlDocument containing multiple XmlNodes. Should I create a single collection like new Meteor.Collection("Documents") and update it as a ...

Using Three JS and WebGl to showcase a sprite overlaid on a panoramic background

I am currently working on developing a user-friendly panorama web application that allows users to rotate in all directions and interact with sprites within the loaded panorama. While I have successfully implemented this functionality in CSS3D using three. ...

Tips for choosing between options in JavaScript and AngularJS

How can I choose the appropriate <select> tag option using JavaScript or AngularJS in the backend? Hint: I receive data from an API service and populate a form for editing. Assuming the gender is currently set as Male in the database, how can I disp ...

Hiding a div using swipe gestures in Angular

What am I trying to achieve? I aim to hide a div when swiped right. This specific action will close the pop-up that appears after clicking a button. What tools are at my disposal? I am utilizing Ionic framework for this task. Within my app.js, I have i ...

alerting the user of any modifications made to a table within the database

In my current Spring project, I am seeking the optimal solution to improve system performance. Should I implement a solution using Javascript or create a custom method in Java? ...

Retrieving specific value from a Parent Controller in AngularJS using UI Router

I have a request to display the value stored in $scope.resAVal on my index.html page. This value is accessible within the RootCtrl. index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <!-- any required JavaScript librarie ...

Construct a new array within a JavaScript constructor function

I have been working on setting up a constructor and trying to initialize an array inside the object that will be created. This specific array is meant to hold multiple objects. function Cluster3DObject(name){ this.name = name; ...

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...

What is the best way to execute methods once subscription data is received?

Exploring the most effective way to execute multiple methods when new data arrives from an Observable, such as an HTTP request, and those methods need to be called with the data. I have been experimenting with two different approaches, but I find drawback ...