Troubleshooting Nested Arrays in JavaScript

I have been receiving API JSON data in a specific format and am currently working on reorganizing it. The goal is to group the data first by the start_date and then by the phys_id. The aim is to showcase the available appointment dates followed by each provider's availability.

"Today"
      Provider Name #1
             2:20pm
             2:40pm
      Provider Name #2
             1:00pm
             2:40pm
"Tomorrow"
      Provider Name #1
             3:20pm
             4:40pm
      Provider Name #2
             12:00pm
             1:40pm

This is how the data is currently structured:

results: [
  {
    start_date: "20191119",
    begintime: "1220",
    appResourceId: "DAD6C44B-3CAC-4BDA-A485-F4BB033FA928",
    appLocationId: "14A1B866-8393-4510-8144-A45B5C4FD07D",
    phys_id: "035B4177-EF4C-492F-86C8-7157B034DB4A"
  },
  ...
]

To group the data by start_date, I've used the following code snippet:

  let group = this.results.reduce((r, a) => {
        r[a.start_date] = [...(r[a.start_date] || []), a];
        return r;
      }, {});
      return group;

The code above helps in structuring the data by start_date, but my next step is to further group the nested array by phys_id so that each provider's available appointment times are displayed. Is there a more efficient way to achieve this, or should I approach it differently?

Answer №1

To optimize the code, I recommend writing a single loop and using a plain object to store the desired levels.

Here is an example:

var data = [
  {
    start_date: "20191119",
    begintime: "1220",
    appResourceId: "DAD6C44B-3CAC-4BDA-A485-F4BB033FA928",
    appLocationId: "14A1B866-8393-4510-8144-A45B5C4FD07D",
    phys_id: "035B4177-EF4C-492F-86C8-7157B034DB4A"
  },
  // More data objects...
];

const group = {};

for (const datum of data) {
    const date = datum.start_date;
    const pId = datum.phys_id;

    if (!group[date]) {
        group[date] = {};
    }

    if (!group[date][pId]) {
        group[date][pId] = [];
    }

    group[date][pId].push(datum);
}

console.log(group);

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

What is the best way to transfer an argument from a parsed JSON value to an onclick function?

In our dataset, we have a specific table that contains valuable information. My main objective is to transfer an argument extracted from parsed JSON data to a separate JavaScript function known as newStory(value['stories']) using the onclick meth ...

Tips for implementing custom fonts in NextJS without relying on external services

Utilizing Fonts in NextJS I have been researching various methods for using self-hosted fonts with NextJS. When attempting the following code, I encountered a [ wait ] compiling ...: @font-face { font-family: 'montserrat'; src: url(&a ...

Troubleshooting issues with TypeScript D3 v4 module import functionality

As I embark on the journey of creating a miniature JS library using D3 to visualize line charts, I find myself navigating unfamiliar waters. However, I believe that deep diving into this project is the most effective way for me to learn. Below is the cont ...

Combining Multiple Properties in a Single-File Component with Vue.js 2

Currently, my project involves Laravel 5.5 & Vue.js 2.x. After extensive research and seeking answers, I began working with components. However, I am encountering a warning message upon page rendering: [Vue warn]: Property or method "trimestral" is not def ...

Function for querying database is not executing in an asynchronous manner

After setting up a function in my node server to handle querying the database and returning results, I found that using async await could help streamline the process throughout my routes. This way, I wouldn't end up with nested queries within one anot ...

Is it possible to dynamically change an ngModel value directly from the component?

I'm currently immersed in an Angular project and my initial file setup was like this: dog.ts: export interface Dog { name: string; age: number; breed: string; } dog.component.ts: import { Dog } from '../dog'; @Component({ //setup ...

Encountered a static symbol values resolution error while working with angular 2 npm link. The issue occurred when the function 'makeDecorator' was being called

Whenever I attempt to use "npm link" to consume a different package I created, I encounter an error while running my application. The error message reads as follows: An error occurred while resolving symbol values statically during the invocation of the ...

Vue.js isn't triggering the 'created' method as expected

I have a main component called App.vue. Within this component, I have defined the created method in my methods object. However, I am noticing that this method is never being executed. <template> <div id="app"> <Header /> <Ad ...

Struggling to retrieve the fake JavaScript data for my Vue.js table

I am a beginner in the development field and encountering the following error report while working with Vue.js 3 115:5 error 'vendorTable' is assigned a value but never used no-unused-vars 115:23 error 'Vue' is not defined no- ...

Bootstrap carousel button that tracks the number of clicks

Unfortunately, I am facing a challenging issue with creating a click counter for the Bootstrap carousel button. The problem seems to be related to the span element for the previous and next icons. The button counter is not registering clicks on the respec ...

Guide on how to reference the Html directory using the path module in Node Js

Desperately trying to send an html file as a response using express, but I'm having trouble locating the position or path of the index.html file. This is how my files are structured - MyWebsite Html index.html Css index.css ...

Extract the last word from a string, filter out any special characters, and store it in an array

Here is the content of the xmlhttp.responseText: var Text = "FS2Crew A320 Checklist_1""FS2Crew Flight Crew A320 Main Ops Manual_1""FS2Crew Flight Crew A320 Main Ops Manual_10""FS2Crew Flight Crew A320 Main Ops Manual_11&q ...

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...

Link PHP with Flex Player for seamless integration

Utilizing the Flex Player component on a local server. The FLV video files are located in bin-debug/Video Source. Here is the PHP code snippet: $id = $_GET["id"]; $media = getDirectoryList("bin-debug/Video Source"); if($media[$id] != null){ ...

What could be causing Vuejs to not update elements promptly?

Currently, I am encountering a scenario where I am adding options to a select element using Vue.js when the @change event of that specific element is triggered. An issue arises where the new option is not 'registered' until I exit the function. ...

Compare the key of one array against the value of another array using jQuery and retrieve any matches

Utilizing $.getJSON to retrieve data from an external .json file containing the following information. { "title_12345":"<span class=\"header-class\">Header</span>", "p_12345":"<span class=\"description-class\"& ...

The use of strcpy() on arrays of structs and their elements does not produce the desired outcome

Struggling with a homework problem for the last 2 hours. I have defined a struct named courses which looks like this: typedef struct { int crn; char course[STR_SIZE]; char course_number[STR_SIZE]; } courses; I have two dynamically allocated arrays ...

Removing Redux State in ReactDeleting data from Redux in a

After displaying a list of data on a table, I have implemented a View component where specific data from the list is passed. However, I am facing an issue when attempting to delete something in the View modal dialog as the redux data delete reducer does no ...

Using JSON within a GraphQL type definition in a Node.js environment

Utilizing Node.js, I am making requests to a report API that returns JSON responses. The API accepts different IDs as parameters, resulting in varying responses. For instance: https://report.domain.io/report/1 https://report.domain.io/report/2 Each r ...

Problem with Bootstrap loading state when certain input fields are required

Just starting out with Bootstrap 3 and looking to integrate the loading state button function into my form. I've set up an input field with the required option as shown below. <form> <input class="input" name="title" type="text" required / ...