Perform second level array grouping in JSON

I need help with grouping at the second level of a JSON string. The code I have works well for one level arrays in the JSON string.

Array.prototype.groupBy = function(keyName) {
  var res = {};
  this.forEach(function(x) {
    var k = x[keyName];
    var v = res[k];
    if (!v) v = res[k] = [];
    v.push(x);
  });
  return res;
};

var myObject = {
      "groups": [{
            "id": "2",
            "name": "test group 1",
            "category": "clinical note",
            "author": "RRP"
        }, {
            "id": "1",
            "name": "test group 2",
            "category": "clinical image",
            "author": "LKP"
        }, {
            "id": "2",
            "name": "test group 1",
            "category": "clinical document",
            "author": "RRP"
        }, {
            "id": "4",
            "name": "test group 4",
            "category": "clinical note",
            "author": "John"
        }]

}

myObject.groups.sort(function(a,b) { return a.author > b.author } );    

var byJob = myObject.groups.groupBy('id');

for (var author in byJob) {
  document.write('<h3>'+author+','+byJob[author].length+'</h3>');
  byJob[author].forEach(function(e) {
    document.write('<p>'+e.id +', '+e.name+'</p>');
  });

Output::

1,1

1, test group 2

2,2

2, test group 1

2, test group 1

4,1

4, test group 4

The above example works well for one level array grouping but I'm looking to implement second level array grouping in a JSON string. For example, consider the following JSON string::

{
    "Category": {
        "old_modi":1,
        "new_modi":1,
        "FORM": [{
            "name":"form1",
            "date":"08/08/2012",
            "location":"abc",
            "PERSON":[{
                "ID":1,
                "author":"xyz"
            }]
        }]
    }
}

Desired output (Author name grouped by form name, date, and location) ::

xyz
  form1 08/08/2012 xyz

If anyone has an idea on how to modify the existing code to achieve this, it would be greatly appreciated.

Thank you in advance..

Answer №1

To iterate through a JavaScript object recursively, it's important to note that the object can be either a JSON object or an array. I personally implemented two separate for-loops to handle each case in my solution, although there may be a simpler way to accomplish this task. Regardless, my approach is capable of handling groupby operations at any level. You can view the code on jsFiddle.

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

Using JavaScript in conjunction with IPFS to verify the 404 status from localhost:8080 and identify if the local IPFS node is active within a browser user script

As a newcomer to IPFS and JavaScript, I have successfully created a simple IPFS userscript that redirects addresses containing *://*/ipfs/* or *://*/ipns/* to http://localhost:8080/<IPFS_HASH>. However, there is an issue when the local IPFS node is ...

Stop displaying AJAX requests in the console tab of Firebug, similar to how Twitter does it

I'm looking for a way to prevent my AJAX calls from being logged in Firebug's Console tab, similar to how Twitter does it. When using Twitter search, you'll see a live update feed showing "5 tweets since you searched." Twitter sends periodic ...

Vue: NavigationDuplicated: Redundant navigation to current location was prevented, requiring a page reload

I have this Hashtag.vue object: <template> <div v-on:click="clicked"> <div class="tag rounded-full p-2 "> {{text}}</div> </div> </template> <script> export default ...

Transformation of callback to promise in JavaScript

I am seeking a way to convert the given callback procedure into a promise. The initial code snippet is as follows: app.get('/api/books', function(req, res) { let booksCallback = function(books) { res.send(books) } DataBase.getBooks( ...

Discover the power of HTML5 canvas by calculating distances and manipulating objects

I have a distance function that returns a value called distance, such as 15, 10, etc. Here is the function: var Distance = function( other ) { var xd = other.x - this.x; var yd = other.y - this.y; return Math.sqrt( xd * xd + yd * yd ); }; I ...

What is the best choice - Json or Xml for Silverlight development?

Currently, I am connecting with multiple services through a SL component using both TCP sockets and HTTP web requests. We are in the midst of a discussion regarding what data format to utilize - JSON or XML. I am curious to know what choices others have m ...

I am interested in verifying whether the added name is already in the array before pushing it again. Regardless, the name will still be pushed into the array

this code snippet is written in HTML <body> <section> <h1>information about client profiles</h1> <div class="madaro" v-on:click.right.prevent> <div> <input v- ...

When using node.js express, the req.body object does not yield any results

My web server setup with express appears to be functioning correctly, however, I am encountering an issue where the req.body returns nothing. Despite not receiving any errors, the console.log(req.body) doesn't show anything in the console output. Stra ...

properties remain unchanged even after the state has been updated

Within my application, I have a component called Player. This component generates a div element containing an image and has properties named x and y. The values of these properties determine the left and top position of the div rendered by Player. Outside ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, I’m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Utilizing the power of ui-views alongside angularjs ui Tabs to handle inappropriate user input

I recently updated the markup for some forms to utilize the angularJS ui Tabs component. The new markup structure is as follows: <div class="col-lg-3 col-md-3 panel-container"> <tabset vertical="true" type="pills"> ...

Display custom modals in React that showcase content for a brief moment before the page refreshes

I recently developed a custom modal in React. When the Open button is clicked, showModal is set to true and the modal display changes to block. Conversely, clicking the Close button sets the display to none. However, I noticed a bug where upon refreshing ...

Obtain the HTML of a Vue component and transmit it using an ajax POST request

I need to send an email with an HTML body using only ajax since I don't have access to the server code. Fortunately, the server has an API for sending emails. Currently, I have a dynamically rendered component called invoiceEmail. sendEmail () { ...

The react-dates component restricts users from choosing dates earlier than the present date

Currently, I am utilizing airbnb's DateRangePicker. The issue is that it does not permit the selection of dates before the current date. Is there a way to modify it so that past dates can be chosen as the start date? You can find the code being implem ...

Customizing HTML 5 Validation Techniques

I am in need of a form that has some specific requirements: It should show validation messages in a custom format instead of the default style. All invalid field bubbles should be displayed at once, rather than one at a time. Currently, I am dealing with ...

Child element performs a method following the componentDidMount lifecycle hook of the parent element

Question regarding React.js components: Parent and Child. import React, { Component, Children, cloneElement } from 'react' import {render} from 'react-dom' class Child extends Component { someMethod() { /* Some code... */ ...

Having issues with my jQuery getJSON function

Encountering a familiar issue once again. I am currently in the process of modifying a function that previously returned an object in the code. Now, I am attempting to retrieve the object from JSON using $.getJSON function getEventData() { var result = ...

Best practice for stopping routing in angular

I am currently working on an angular application that includes guest functionality. This feature allows me to create a guest account for all unauthorized users in the background. I need to pause routing until the guest account is created and then specify a ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

Instructions on creating an individual DropdownIndicator component with React-select for the purpose of reusability in different sections of the project

The code below functions properly when the DropdownIndicator component is kept in the same file. However, I am interested in separating DropdownIndicator into its own file so that it can be reused. This way, it can be used as a separate component and incl ...