Grouping JSON data in Javascript, such that multiple fields are returned within the parent object

I am currently exploring how to perform a groupBy operation on a JSON file that contains a unique identifier for the field I want to group by. The goal is to return the grouped information as a new object while also preserving some fields from the original JSON object.

Here's the initial data:

[{
  StoreId: 1,
  StoreName: "Adventure Works",
  StoreCity: "New York",
  FirstName: "John",
  LastName: "Smith",
  EmployeeId: 1,
  EmployeeAge: 25
},{
  StoreId: 1,
  StoreName: "Adventure Works",
  StoreCity: "New York",
  FirstName: "Jane",
  LastName: "Doe",
  EmployeeId: 2,
  EmployeeAge: 30
},{
  StoreId: 2,
  StoreName: "Amazon",
  StoreCity: "Seattle",
  FirstName: "Jeff",
  LastName: "Bezos",
  EmployeeId: 1,
  EmployeeAge: 30
}]

The desired output should look like this:

[{
  StoreId: 1,
  StoreName: "Adventure Works",
  StoreCity: "New York",
  Employees: [{
              FirstName: "John",
              LastName: "Smith",
              EmployeeId: 1,
              EmployeeAge: 25
              },{
              FirstName: "Jane",
              LastName: "Doe",
              EmployeeId: 2,
              EmployeeAge: 30
              }]
   },{
   StoreId: 2,
   StoreName: "Amazon",
   StoreCity: "Seattle",
   Employees: [{
                FirstName: "Jeff",
                LastName: "Bezos",
                EmployeeId: 1,
                EmployeeAge: 30
               }]
}]

Answer №1

Here is the solution for you...

const data = 
  [ { StoreId: 1, StoreName: 'Adventure Works', StoreCity: 'New York', FirstName: 'John', LastName: 'Smith', EmployeeId: 1, EmployeeAge: 25 } 
  , { StoreId: 1, StoreName: 'Adventure Works', StoreCity: 'New York', FirstName: 'Jane', LastName: 'Doe',   EmployeeId: 2, EmployeeAge: 30 } 
  , { StoreId: 2, StoreName: 'Amazon',          StoreCity: 'Seattle',  FirstName: 'Jeff', LastName: 'Bezos', EmployeeId: 1, EmployeeAge: 30 } 
  ] 

const groupedData = data.reduce((accumulator,currentValue,index)=>
  {
  let {StoreId,StoreName,StoreCity,FirstName,LastName,EmployeeId,EmployeeAge} = currentValue
  if (accumulator.key!== StoreId)
    {
    accumulator.key = StoreId
    accumulator.idx = accumulator.result.push( {StoreId, StoreName, StoreCity, Employees: [] }) -1
    }
  accumulator.result[accumulator.idx].Employees.push( {FirstName, LastName, EmployeeId, EmployeeAge}) 
  return (index===accumulator.maxIndex) ? accumulator.result : accumulator
  }
  ,{key:null, idx:null, maxIndex:data.length -1, result:[]}
  )

console.log( JSON.stringify(groupedData,0,2) )
.as-console-wrapper { 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

Tips for retrieving reverse geocodes using PHP cURL and JSON:

How can I echo only the formatted address from a JSON response using PHP? Here is the code I currently have: <?PHP $ch = curl_init(); $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=22.569794,88.357934'; curl_setopt($ch, CUR ...

Problems with scrolling in Firefox when using Three.JS

Is anyone else experiencing issues with three.js? I have a simple demo of a spinning cube with varying rotational velocity using arrow keys, mouse, or touch input. Everything works perfectly in Chrome, but the textures are spliced and not mapped correctly ...

Insert, delete, and modify rows within the table

I'm struggling with a JavaScript issue and could use some help. How can I add a new row for all columns with the same properties as the old rows, including a "remove" button for the new row? Is there a way to prevent editing cells that contain b ...

Unable to use import or require statements in AWS Lambda

I am currently working on setting up a lambda function on AWS. My goal is to store user data into my MongoDB database after they sign up. I decided to trigger the lambda function using the "pre authenticate" method. However, I encountered an error message ...

Receiving a `combined` error when updating Meteor isopacket - sourcemapConsumer.destroy function is not recognized

Whenever I attempt to update or create a project using Meteor version 1.9 and above, I encounter the following error: Errors prevented isopacket load: While loading isopacket `combined`: C:\Users\USER\AppData\Local\.meteor\p ...

The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database. Javascript Function function changeDepartment() { // Initializing and assigning variables va ...

Efficient Pagination with React Redux

Case One: I am currently implementing server-side pagination in Rails using React for the front-end and Redux for state management. I have completed all the necessary setup, and the only thing left is to pass the newly generated URL to fetch the new data. ...

An alert box displays N times when the submit button is clicked N times

Consider the following function: function validateForm() { var elements = ["firstname", "lastname", "password", "favfood", "favsport"]; document.getElementById('register').setAttribute('noValidate', true); document.getElement ...

Converting Datatable to JSON in C#

I am presenting a data table layout as shown below: Subject Question Qtype English xxxxxxx Subjective English yyyyyyy Subjective English zzzzzzz Objective English sasasas Objective English cvcvcvv Subjective The 'Question' column ...

Using Aurelia's one-way binding technique with a checkbox

I am searching for a method to bind a checkbox in Aurelia one-way, while still allowing the user to click on the checkbox. Imagine a view similar to the one below that shows one selectable item from a list: <template> <div click.trigger="sel ...

Handling form submissions in Vue.js before navigating away from the current route

As a newcomer to VueJs, I am facing a problem with creating a form. My goal is to display an alert dialog with the message "you might lose the data, please save the data before you leave," and upon clicking 'yes', the form should be submitted and ...

tilt and give motion to image within canvas

I am looking to incorporate skewing and animation effects on an image displayed on a canvas. While I have successfully drawn the image on the canvas using the code snippet below, I am unsure about how to apply skewing and animation to the image post-drawin ...

Firefox version 78.0.1's Responsive Design Mode fails to provide accurate window.innerWidth values after screen orientation change

Could this be a bug specific to Firefox, or have I made an error somewhere? When testing in Chrome or on an actual device like Android, everything works fine. It appears to be an issue only when using Firefox's Responsive Design Mode. Below is the c ...

Exploring additional parameters within express.js

I'm currently working on creating an email sender that includes all necessary components such as 'from', 'to', 'subject', 'textBody', etc. However, I am facing a challenge in setting optional parameters in expre ...

The functionality of JQuery ceases to function properly once the BxSlider plugin is activated

I've encountered a strange issue while using the BxSlider plugin of jQuery on my page. When I implement the code for the slider with BxSlider, all other custom functions seem to stop working without any errors being displayed in the console. I've ...

Looking to extract the name of a variable and its corresponding data from a JSON file using C#?

Here is an example of Json: { "typeOfDriver": "selenium", "goToURL": "url", } Currently, I am working on a way to extract the first variable name "typeOfDriver". The code I am using only retrieves the data from the element. Sample Code: dynamic loadCon ...

Issues Persist with Updating mySQL Database using PHP

I've been attempting to insert location data into a MySQL database using my PHP server from the TripTracker Android App. However, despite trying different approaches in PHP, I have not been successful so far. Any assistance would be much appreciated. ...

Is there a way to programmatically prevent the back button from functioning if the previous route pathname in React was 'Login'?

When it comes to navigating back on previous pages, the traditional back button is typically used instead of relying solely on the navigation bar. However, I am currently looking to disable this feature specifically when the next previous route in line is ...

Trouble with Converting Array Elements into a Div Tag

Could you please review this code and let me know why I am having trouble adding the array items to the .box element? I have tried using both .text() and .html(). var letters = []; var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; letters ...

Encountering an issue with a class component stating that "this.setState is not a function

I am currently learning React JS and encountered an error when calling my first API in React. I keep getting the message "Unhandled Rejection (TypeError): this.setState is not a function." I have been trying to troubleshoot this issue on my own but haven ...