arrange items based on their category into arrays

I have a JSON file that needs to be arranged based on three specific fields.

Here is an example snippet of the JSON data:

{
  "Racename": "10KM",
  "Category": 34,
  "Gender": "Male",
  "Work": "Google",
  "FullName": "Dave Happner",
  "Rank": 1,
  "Ponit": 1,
  "Numparticipant": 0,
  "rankparticipant": 0,
  "precentagePart": "0",
  "NumRaces": 1,
  "RaceTime": "2018-10-18T00:34:20",
  "rankCat": 1,
  "PointCat": 1,
  "RaceDate": "2018-10-05"
}

The desired output (using underscore or lodash) should be structured like this:

 [
                {
                    "Racename" : "10KM",
                    "Category": "34",
                    "Gender": "Male",
                    runner : [
                        {
                            "Work": "Google",
                            "FullName": "Dave Happner",
                            "Rank": 1,
                            "Ponit": 1,
                            "Numparticipant": 0,
                            "rankparticipant": 0,
                            "precentagePart": "0",
                            "NumRaces": 1,
                            "RaceTime": "2018-10-18T00:34:20",
                            "rankCat": 1,
                            "PointCat": 1,
                            "RaceDate": "2018-10-05"
                        }
                    ]
                }
            

Answer №1

To transform your data into an object organized by specific criteria, you can use the reduce method with a unique key constructed from the values of certain properties. For example, by combining the Racename, Category, and Gender fields separated by an uncommon character like _, you can create keys such as 10KM_34_Male. During each iteration, check if the key already exists - if not, initialize it with an empty runner array before adding the current data to it.

After processing with reduce, you can extract the object's values to obtain the desired array output:

const inputData = [{
  "Racename": "10KM",
  "Category": 34,
  "Gender": "Male",
  "Work": "Google",
  "FullName": "Dave Happner",
  "Rank": 1,
  "Point": 1,
  "NumParticipants": 0,
  "RankParticipant": 0,
  "PercentagePart": "0",
  "NumRaces": 1,
  "RaceTime": "2018-10-18T00:34:20",
  "RankCat": 1,
  "PointCat": 1,
  "RaceDate": "2018-10-05"
}];

const transformedDataObj = inputData.reduce((acc, { Racename, Category, Gender, ...rest }) => {
  const key = [Racename, Category, Gender].join('_');
  if (!acc[key]) {
    acc[key] = { Racename, Category, Gender, runner: [] };
  }
  acc[key].runner.push(rest);
  return acc;
}, {});
const outputArray = Object.values(transformedDataObj);
console.log(outputArray);

You can apply this method to larger datasets as well:

const inputData = [{
  "Racename": "10KM",
  "Category": 34,
  "Gender": "Male",
  "Work": "Google",
  "FullName": "Dave Happner",
  "Rank": 1,
  "Point": 1,
  "NumParticipants": 0,
  "RankParticipant": 0,
  "PercentagePart": "0",
  "NumRaces": 1,
  "RaceTime": "2018-10-18T00:34:20",
  "RankCat": 1,
  "PointCat": 1,
  "RaceDate": "2018-10-05"
},{
  "Racename": "10KM",
  "Category": 34,
  "Gender": "Male",
  "Work": "Amazon",
  "FullName": "Bob Joe",
  "Rank": 12,
  "Point": 2,
  "NumParticipants": 0,
  "RankParticipant": 0,
  "PercentagePart": "0",
  "NumRaces": 1,
  "RaceTime": "2018-10-18T00:34:20",
  "RankCat": 1,
  "PointCat": 1,
  "RaceDate": "2018-10-05"
},{
  "Racename": "20KM",
  "Category": 40,
  "Gender": "Male",
  "Work": "Google",
  "FullName": "Dave Happner",
  "Rank": 1,
  "Point": 1,
  "NumParticipants": 0,
  "RankParticipant": 0,
  "PercentagePart": "0",
  "NumRaces": 1,
  "RaceTime": "2018-10-18T00:34:20",
  "RankCat": 1,
  "PointCat": 1,
  "RaceDate": "2018-10-05"
}
];

const transformedDataObj = inputData.reduce((acc, { Racename, Category, Gender, ...rest }) => {
  const key = [Racename, Category, Gender].join('_');
  if (!acc[key]) {
    acc[key] = { Racename, Category, Gender, runner: [] };
  }
  acc[key].runner.push(rest);
  return acc;
}, {});
const outputArray = Object.values(transformedDataObj);
console.log(outputArray);

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

Issue with Angular 5 Application - "Implementations cannot be declared in ambient contexts"

Recently in my Angular 5 project, I started encountering an issue with the observable object. Everything was working smoothly until about a week ago when I began receiving this error message: ERROR in node_modules/rxjs/Observable.d.ts(20,31): error TS1183 ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

Troubleshooting Navigation Bar Toggle Button Issue in Bootstrap 5

Currently, I am in the process of working on a web project that requires the implementation of a responsive sidebar. This sidebar should be toggleable using a button located in the navigation bar. My choice for the layout is Bootstrap, and I have come acr ...

Employing useEffect within Material-UI tabs to conceal the third tab

At the page's initial load, I want to hide the first two tabs. The third tab should be visible with its content displayed right away. Currently, I can only see the content after clicking on the third tab. To troubleshoot this issue, I attempted to use ...

Preventing Flash of Unstyled Content in ElectronJS Browser Windows

Upon creating a new BrowserWindow and utilizing loadURL to incorporate an html file within the renderer, there is a brief instance where unstyled content is displayed for approximately half a second before the css is loaded. window.loadURL('file://&a ...

Having issues with $timeout functionality in angular.js

I've implemented $timeout in my controller but it doesn't seem to be functioning correctly. app.controller("Friendsrequests",['$http','$log','$location','$timeout','$scope', function($http,$log,$ ...

Incorporate a personalized array into Google Autocomplete Places using AngularJS

I'm working on my application and I've implemented autocomplete for Google Places using the gm-places-autocomplete directive. However, I would like to enhance this autocomplete feature by incorporating my custom array of locations along with the ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

How can I make the input box TextField in Material UI with React expand to full width when selected?

I am currently customizing a Material UI form where the input box (Text Field) starts off at a width of 200px. My goal is to have the input box expand to 100% width only when it is selected or clicked on. ... <FormGroup sx={{ maxWidth: "200px" ...

Tips for incorporating the Sanitize library into Angular 6:

What is the most effective library for sanitization in Angular 6 to enhance security measures? Since injecting dependencies can be tricky, what are some recommended methods for implementing this in an Angular 6 project? ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

Avoiding redundant requests with the same parameters in Angular/NGRX

Imagine having a component designed to showcase a list of actors from a movie. When this component loads, it triggers an action to retrieve the actors' data. actors.component.ts @Input() filter; // for example, only displaying male actors ngOnInit( ...

Click to refresh a different component in ReactJS

My goal is to create a unique media player that can reload when a user wants to listen to an MP3 file. The concept is as follows: In media-player.js: - Display title, artist, and album art In programs.js: there is a button (LISTEN) that renders in medi ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

"Keep the div locked to the screen when the bottom of the div aligns with the

Hey everyone! I'm currently grappling with a project that requires me to keep a div stuck to the screen (prevent scrolling) when its bottom reaches the bottom of the screen. I have two divs on the page, both with varying heights. My aim is to keep div ...

Is it possible to set up a PHP variable within a JavaScript function?

In the code snippet above, we have a JavaScript function that is used for validation. I am looking to set a PHP variable within the else statement. function validate() { if(document.loginForm.vuser_login.value==""){ alert("Login Name name ca ...

How come an <a> tag is nabbing mouse clicks from a <canvas> element?

I have been experimenting with creating a 3D piano using three.js. Here is a snippet of the code I am currently working on: let renderer, camera, scene, light, keys, selectedKey; init(); render(); function init() { // Code for initializing renderer, ...

Angular's unconventional solution to Firebase

I've been having trouble integrating Firebase with Angular. When I encountered an error stating that firebase.initializeApp is not a function, I hit a roadblock. const firebase = require("firebase"); (Previously, it was written as: import * as fireb ...

Displaying the active navigation element in ApyCom JavaScript jQuery menu: tips and tricks

Currently, I am utilizing the jQuery navigation menu from ApyCom. Everything seems to be functioning properly except for one issue. Whenever I click on a different navigation element, I expect that element to remain highlighted in order to indicate to the ...

Tips for passing mapped data as props to a different component in a React application

I am trying to pass mapped data as props to another component. The code I have written is as follows: <div className={styles.myTeamFlex}> {userTeams.map((team, index) => ( <TeamCard key={team + index} active={active} in ...