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

`HTTP Streaming with Axios in a Node JS Environment`

I am currently facing an issue while attempting to stream price data via HTTP (I'm surprised they aren't using websockets..). I usually use axios for making REST API requests, however, I am struggling to handle 'Transfer Encoding': &apo ...

Errors in the @babel/types during the ng build process in Angular version 8.2.14

When I execute the command 'ng build' for my Angular App, I encounter the following errors: ERROR in ../node_modules/@types/babel-types/index.d.ts:1769:96 - error TS1144: '{' or ';' expected. 1769 export function assertArrayE ...

When the URL is modified, triggering an event to load

Is there a way to make a page load directly to a specific section and automatically open an accordion? For instance, I have a page with multiple accordions displayed vertically. I already know that using id's in the URL like page#accordion1 will scro ...

After the page is reloaded, apply a class to the divs by selecting them based on the "data" attribute

I have a set of four cards labeled "card", each representing different body parts: eyes, torso, arms, and legs. <div class="card" data-lesson="eyes">eyes</div> <div class="card" data-lesson="torso">torso</div> <div class="card" ...

Ajax failing to trigger upon submission

I need assistance in creating a form that will first submit via AJAX before directing to a specified URL. Once submitted, an email should be sent to me through newsletter.php <script type='text/javascript'> $(function () { $("#signup") ...

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

Issues related to .maps and the use of import 'rxjs/add/operator/map';

Having an issue with Angular 4 and rxjs/add/operator/map. Even after importing rxjs/add/operator/map, I am unable to use .map. Visual Basics keeps displaying two error messages: message: 'Declaration or statement expected.' message: 'Cannot ...

Converting a string to a number in an Angular template

Within my select box, I am capturing the selected value and binding it to the variable startingYear. However, I need the type of startingYear to be a number, but it is currently registering as a string. Is there a way to convert it to a number? console ...

Why is it so difficult for the TypeScript compiler to recognize that my variables are not undefined?

Here is the code snippet in question: function test(a: number | undefined, b: number | undefined) { if (!a && !b) { console.log('Neither are present'); return; } if (!b && !!a) { console.log('b is not present, we ...

Node.js is throwing GitHub API 401 Bad Credentials error, whereas curl is not encountering the

I am attempting to authenticate on Enterprise GitHub using @octokit/rest. When I execute the following Curl command, I receive a list of API URLs: curl -u "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80edf9c0e5ede1e9ecaee3e ...

Unable to redirect to the initial page successfully

My React application is using Redux-Toolkit (RTK) Query for user login functionality. When the user clicks the "logout" button, it should redirect to the home page ("/"). However, I'm facing an issue where clicking the "logout" button does not trigger ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Establishing a Recyclable Testing Rendering Method in redux toolkit version 2

In the era of Redux Toolkit v2, a noticeable change occurred with the absence of the EmptyObject type and the unavailability of the PreloadedState type in the @reduxjs/toolkit package. This has led to a requirement of defining all reducers inside the pre ...

Enhancing user experience with VideoJS player overlay buttons on mobile devices

I am currently using VideoJs player version 4.2. When I launch a videojs player on Safari browser in an iOS device, it defaults to native controls. However, when I pause the player, overlay buttons (links to navigate to other pages) are displayed on the v ...

Using child routes in eager loaded components can be achieved without making any changes to

In many tutorials, I have noticed that RouterModule.forChild(..) is commonly used for lazy loading. However, I am of the opinion that this forChild method can also be utilized for eager loading. Its advantage lies in the fact that routes can be configured ...

Encountered an issue while trying to send an email through the Gmail API: Unfortunately, this API does not provide

I am attempting to use the Gmail API to send emails. I collect user data and convert it to a base64url string. After obtaining the raw value, I attempt to send the email using a POST request. var ss=new Buffer(message).toString('base64') var ...

Issues with CSS Modules not applying styles in next.js 13 version

Employing next.js 13.1.1 along with /app Previously, I had been handling all of my styles using a global.css, however, I am now attempting to transition them into CSS Modules. Within my root layout.js, there is a Header component that is imported from ./ ...

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

In order to comply with JSX syntax rules in Gatsby.js, it is necessary to enclose adjacent elements

I want to apologize beforehand for the code quality. Every time I attempt to insert my HTML code into the Gatsby.js project on the index.js page, I encounter this error: ERROR in ./src/components/section3.js Module build failed (from ./node_modules/gatsb ...

What is the best way to modify the KeyName in an object?

Having difficulty parsing an Object by changing keynames due to the error message "Element implicitly has an 'any' type because expression of type 'keyof SignInStore' can't be used to index type '{}'". interface SignInSto ...