What is the best way to organize data in JavaScript?

My JS application needs to display data in a specific order.

The process:

Users select sectors first, resulting in sector data based on their choices like,

const selectedSectors = [{sectorName: "Sector One", sectorId: 5}, {sectorName: "Sector Two", sectorId: 24}]

We already have department and job title data, and we retrieve matching records using the code below,

// code block here

The above code produces the following result,

Current Output:

// output goes here

The output aligns with expectations. However, I need to include the data along with the corresponding Sectors.

So based on sector selection by the user, the respective departments and job titles should be displayed.

The expected structure is as follows,

Expected Output:

// expected output structure

Based on the provided data, it's evident that sector ID 5 has two departments (Production and Design/Engineering), while sector ID 24 has two different departments (Consulting and Administration).

// additional code snippet

I can filter and group job titles based on DepartmentID but struggle with grouping departments by sector ID.

Hint: The selectedSectors and departments variables contain the sectorId.

Any assistance in achieving the expected outcome is greatly appreciated. Thank you!

Answer №1

    const chosenIndustries = [{industryName: "Industry One", industryId: 5}, {industryName: "Industry Two", industryId: 24}]

    const departments = [{"DepartmentID":51,"IndustryID":5,"Name":"Manufacturing","SortOrder":1},{"DepartmentID":52,"IndustryID":5,"Name":"Design/Engineering","SortOrder":2},{"DepartmentID":92,"IndustryID":24,"Name":"Consulting","SortOrder":8},{"DepartmentID":114,"IndustryID":24,"Name":"Administration","SortOrder":5}]

    const jobTitles = [{"JobTitleID":167,"DepartmentID":51,"JobName":"Production Manager","Deleted":false,"SortOrder":5},{"JobTitleID":294,"DepartmentID":52,"JobName":"Senior Designer","Deleted":false,"SortOrder":5},{"JobTitleID":178,"DepartmentID":51,"JobName":"Supervisor","Deleted":false,"SortOrder":3},{"JobTitleID":191,"DepartmentID":92,"JobName":"Shop Supervisor","Deleted":false,"SortOrder":1},{"JobTitleID":461,"DepartmentID":114,"JobName":"Sawyer","Deleted":false,"SortOrder":7},{"JobTitleID":461,"DepartmentID":66,"JobName":"Carpenter","Deleted":false,"SortOrder":7},{"JobTitleID":474,"DepartmentID":92,"JobName":"Designer - Part Time","Deleted":false,"SortOrder":11},{"JobTitleID":449,"DepartmentID":51,"JobName":"Wall Panel Designer","Deleted":false,"SortOrder":15},{"JobTitleID":278,"DepartmentID":114,"JobName":"Manager","Deleted":false,"SortOrder":2}]
        
        
    const filteredData = chosenIndustries.map(industry =>  {
 const deps = departments.filter(dep => dep.IndustryID === industry.industryId).flatMap(department => {
    const jobtitles= jobTitles.filter(
       (jobTitle) => jobTitle.DepartmentID === department.DepartmentID
    );
      const newObj = {
          deptName: department.Name,
          jobtitles,
      };
     return newObj;
    })
return {
  industryId: industry.industryId,
  industryName: industry.industryName,
  departments: deps,
}
});

    console.log('filteredData ', filteredData)

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

Disable event listener when the controls are unlocked using the pointerlock controls in three.js

While navigating a model with threejs pointerlock controls, clicking on specific sections of the model directs users to different parts of the site. However, an issue arises when the camera is centered over a section and the user exits the pointerlock. Upo ...

avoiding retrieval of historical data in mongodb atlas using a Node.js application

It's been 10 days since I last used mongodb atlas. When I try to connect my node application after this time, it returns a blank array in the find Query from Node application. However, when I insert new data into mongodb atlas using the Node applicati ...

Tips for creating a variable using an array

I am attempting to store array items in an array. Below is my code; $sqlText['attach']="SELECT attachments.disk_directory, attachments.disk_filename, attachments.digest, attachments.filename ...

Customizing alert message styles in Java script: Changing color and font of specific parts

I have been attempting to change a specific part of text to be bold and displayed in red color. Unfortunately, this does not seem to work on Microsoft Edge. Here is my code: alert("Hi how are you my friend"); The section that needs to be formatted: "fri ...

Summing numbers inputted into text boxes generated by a looping mechanism

Currently, I have a function that uses a for loop to generate multiple text boxes dynamically. Each row consists of three text boxes created using the same ID, all within an HTML table structure. var txtBox = "<input type='text' id='txtN ...

Endless Loop: AngularJS app.run() Promise caught in infinite cycle

I have a situation in my AngularJS app where I am using app.run() to check if a user is logged in before displaying the site to restrict access to non-registered users. Initially, I faced issues with the isLoggedIn function returning false when reloading t ...

Accurate linking to the interface while retrieving information from a specified URL

Just started with Angular and attempting to assign the returned json data to my interface, but it's not working as expected. Check out the code I'm using below: Stackblitz Json URL ...

Enabling draggable functionality for divs using JSPlumb and a toggle button

http://jsfiddle.net/taoist/fsmX7/ The scenario presented in the code snippet above involves toggling the draggable state of the .textDivContainer element based on user interaction. The desired behavior is for the element to be non-draggable by default, an ...

Is it possible for Javascript to manipulate the DOM of an Ajax text/html response?

My goal is to implement Ajax to retrieve an HTML page and extract a specific div by its ID, then insert that div into the current page. This involves loading a second page via Ajax, extracting the specified div from the response, and placing it within th ...

Retain elements in a numpy array that meet multiple conditions or criteria

Is there a more efficient way to keep values of an array that satisfy multiple conditions? For example: a = np.array([1,3,5,6,4,6,7,8,9]) If I want to filter out values that are greater than 3 and less than 7, my desired output would be: array([5, 6, 4, ...

What is the process for modifying event (hover & click) on a legend item within highcharts?

When hovering over chart points, you can see the point value in the center of the pie chart. Similarly, when you stop hovering over a chart point, you can see the total value displayed. This behavior also applies when hovering over a legend item. const cha ...

I am facing issues with jQuery's live and livequery functions when trying to use them with a form that is being loaded dynamically through

Previously, I inquired about a related issue regarding attaching behavior to an element with jQuery after insertion. However, I have not yet found a solution. For clarity's sake, I am posing a new question with a different scenario. Below is the code ...

Having trouble with jQuery animate function?

I have been struggling to get my animate function to work, despite looking at multiple similar posts and making modifications to my code. My goal is to make an image of a plane move from left to right across the screen and stop halfway. Here is the code I ...

Using jQuery and PHP to submit a form

I'm attempting to trigger a form submission when a button on another form is clicked. The goal is to update the form without losing any previously entered data. It's important to note that these forms are not exactly the same, but for the sake o ...

Exploring JavaScript's Modules, Enclosures, and Scoping

Utilizing a closure pattern to compartmentalize my code: (function(root) { // MODULE CODE HERE if (typeof module !== 'undefined' && module.exports) { // CommonJS /* var dependencies = require(...) */ module.exports = myModu ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

Python implementation of dynamic N-dimensional finite difference computation along a specific axis

I am working on a function that calculates the finite difference of a 1d np.array and I am looking to expand it to work with n-dimensional arrays. The current function looks like this: def fpp_fourth_order_term(U): """Calculates the second derivative ...

"I have successfully removed the URL from index.html. However, I am now wondering how I can include them in app

I have modified the URL in index.html to remove query parameters, but now I need my app.component.ts file to still be able to access and work with those query params using ActivatedRoute. However, when I implemented the script in index.html to remove query ...

Transforming a sophisticated nested array containing named values into JSON format

I am facing a challenge with converting an array into JSON format. The array, named classProfiles, has the following structure (seen after inspecting console output): Buildings_clear: Array(0) band1: [Min: 24, Max: 24, Mean: 24, Median: 24, StdDev: 0] ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...