Use a combination of the reduce and map functions in JavaScript to transform a one-dimensional array into a multi-dimensional array

Below is an array containing mySQL results:

    [
        {"eventId":"84","shootId":"72","clubEventId":"253","clubId":"7"},
        {"eventId":"84","shootId":"72","clubEventId":"254","clubId":"5"},
        {"eventId":"84","shootId":"72","clubEventId":"255","clubId":"6"},
        {"eventId":"85","shootId":"72","clubEventId":"256","clubId":"7"},
        {"eventId":"85","shootId":"72","clubEventId":"257","clubId":"5"},
        {"eventId":"85","shootId":"72","clubEventId":"258","clubId":"6"}
   ]

I am seeking a way to efficiently convert this using a reduce function into the following structure:

{
  "84" : {
    "clubEvents" : {
      "253" : {
        "clubEventId" : 253,
        "clubId" : 7 },
      "254" : {
        "clubEventId" : 254,
        "clubId" : 5 },
      "255" : {
        "clubEventId" : 255,
        "clubId" : 6}
    },   
    "shootId" : 72,  
  },
  "85" : {
     "clubEvents" : {
      "253" : {
        "clubEventId" : 256,
        "clubId" : 7 },
      "254" : {
        "clubEventId" : 257,
        "clubId" : 5 },
      "255" : {
        "clubEventId" : 258,
        "clubId" : 6}
    },
    "shootId" : 72,
   }
}

Your help on this matter would be greatly appreciated.

Answer №1

If you want to organize your assignments with two levels of nesting, one approach is to use the following code:

const
    data = [{ eventId: "84", shootId: "72", clubEventId: "253", clubId: "7" }, { eventId: "84", shootId: "72", clubEventId: "254", clubId: "5" }, { eventId: "84", shootId: "72", clubEventId: "255", clubId: "6" }, { eventId: "85", shootId: "72", clubEventId: "256", clubId: "7" }, { eventId: "85", shootId: "72", clubEventId: "257", clubId: "5" }, { eventId: "85", shootId: "72", clubEventId: "258", clubId: "6" }],
    result = data.reduce((r, { eventId, shootId, clubEventId, clubId }) => {
        r[eventId] ??= { clubEvents: {}, shootId };
        r[eventId].clubEvents[clubEventId] = { clubEventId, clubId };
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Utilizing the power of reduce method

const data = [
  { eventId: "84", shootId: "72", clubEventId: "253", clubId: "7" },
  { eventId: "84", shootId: "72", clubEventId: "254", clubId: "5" },
  { eventId: "84", shootId: "72", clubEventId: "255", clubId: "6" },
  { eventId: "85", shootId: "72", clubEventId: "256", clubId: "7" },
  { eventId: "85", shootId: "72", clubEventId: "257", clubId: "5" },
  { eventId: "85", shootId: "72", clubEventId: "258", clubId: "6" },
];

const output = data.reduce((accumulator, currentItem) => {
  const { eventId, shootId, clubEventId, clubId } = currentItem;
  if (!accumulator[eventId]) {
    accumulator[eventId] = {
      clubEvents: {
        [clubEventId]: { clubEventId, clubId },
      },
      shootId,
    };
  } else {
    const obj = accumulator[eventId];
    obj["clubEvents"][clubEventId] = { clubEventId, clubId };
  }
  return accumulator;
}, {});

console.log(output);

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

Showing JSON information in an Angular application

Upon page load, I am encountering an issue with retrieving and storing JSON data objects in Angular scope for use on my page and in my controller. When attempting to access the value, I receive the error message: angular.js:11655 ReferenceError: data is ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

What's the reason for this Ajax request taking such a long time to display on the

My webpage features dynamic content created by Ajax, refreshing every 30 seconds with new information from the database. The PHP side of things seems to be functioning properly, but I suspect there might be an issue either in my JavaScript code or within t ...

Javascript error specific to Internet Explorer. Can't retrieve the value of the property 'childNodes'

After removing the header information from the XML file, the issue was resolved. Internet Explorer did not handle it well but Firefox and Chrome worked fine. An error occurred when trying to sort nodes in IE: SCRIPT5007: Unable to get value of the proper ...

Adding content to the parent element immediately after it is generated using jQuery

Is there a way to trigger $(e).append() as soon as the element e is created without using setTimeout()? I find that method inefficient. Are there any DOM events that can detect changes in a subtree of a DOM element? Usually, I would just add the code to t ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

Leveraging the $broadcast method within a $interval function in AngularJS

After extensively searching this site and using Google, I have been unable to find a solution. I have one module dedicated to services and another for the app itself. In the services module, I have the following code snippet: $interval(function(){ $ro ...

Organizing elements in JavaScript

By utilizing d3.nest, I've organized this list through element grouping from another list. array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", E ...

Having all elements at the same height

I am looking to enhance my JavaScript code to only impact 4 items at a time. The goal is to target the first 4 instances of .prodbox, adjust their height accordingly, then move on to the next set of 4 and repeat the process. This sequential adjustment will ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...

Encountering an 'Unknown provider' error while running a unit test with AngularJS and Jasmine

I am facing an issue while writing a unit test for a controller in my application. Jasmine is showing an 'Unknown provider' error related to a provider I created for fetching template URLs. This provider is injected into a config function that is ...

Using jQuery to handle multiple buttons with the same ID

Is there a way to address the issue of multiple buttons sharing the same id? Currently, when clicking on any button, it only updates the record with id=1. How can this problem be resolved? div id="ShowPrace"> <?php try { $stmt = $pdo->prepare(" ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

Ways to emphasize a particular <li> element?

Currently, I am delving into the world of React and facing a challenge. I have been trying to solve the issue below: When fetching some JSON data, it appears in this format: [ { "answerOptions": [ "Answer A", "Answer B", ...

Error: Attempting to access property 'propeller' of an undefined object has caused a TypeError

I am working on a tutorial that can be found at this link: https://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/ During the process, I encountered an error message: Uncaught TypeError: Cannot read property 'propeller& ...

What is the best way to organize an array inside a jQuery .each loop?

I am currently utilizing a .each loop to iterate through various div elements and extract the values from specific input boxes contained within them. Each div represents a row and is identified by an Id, such as plot1, plot2.... I aim to collect all this d ...

Tips for optimizing the speed of uploading multiple images/files from a client's browser to a server using JavaScript

We are seeking ways to enhance the file upload process in our application, particularly for managing large files. Any suggestions on accelerating this process would be greatly appreciated. ...

updating an object using its instance in angular: step-by-step guide

Having multiple nested arrays displaying data through HTML recursion in Angular, I am faced with the task of updating specific fields. Directly editing a field is simple and involves assigning its instance to a variable. arr=[{ "name":"f ...

"Encountered an issue while serializing the user for session storage in Passport.js. Have you already implemented code for

I have recently started learning nodejs and I am currently working on creating a login system. I followed the code for serializing the user from the passport documentation and placed it in config/passport.js. However, I keep encountering the error "Failed ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: https://i.sstatic.net/RL3w4.gif I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for th ...