Group the JSON data by counting values and then output the result as a key-value pair in JSON

After analyzing the JSON data below:

"rows": [{  
        "createdDate": "3/11/2016",
        "createdBy": "Bob"          
    },{ 
        "createdDate": "3/12/2016",
        "createdBy": "Megan"            
    },{ 
        "createdDate": "3/12/2016",
        "createdBy": "Bob"          
    },{ 
        "createdDate": "3/13/2016",
        "createdBy": "Sam"          
    },{ 
        "createdDate": "3/11/2016",
        "createdBy": "Bob"          
    },]

I am in need of a way to group and count different properties for charting purposes. For example, I want output based on 'createdBy' as shown below:

"result": [{
        "key": "Bob",
        "value": 3,         
    },{
        "key": "Megan",
        "value": 1,         
    },{
        "key": "Sam",
        "value": 1,         
    },

Although I attempted to use _groupBy from underscore library, I was unable to achieve the desired result with my JSON data manipulation.

Answer №1

To simplify the task, we can condense rows to tally the occurrences of each object based on the createdBy property. The resulting occurrences object will contain keys representing names (such as Bob1, Megan, etc.) and their corresponding count of occurrences. We can then iterate through this object using Object.keys() and map it to a new result:

var rows = [
    { 'createdDate': '3/11/2016', 'createdBy': 'Bob' },
    { 'createdDate': '3/12/2016', 'createdBy': 'Megan' },
    { 'createdDate': '3/12/2016', 'createdBy': 'Bob' },
    { 'createdDate': '3/13/2016', 'createdBy': 'Sam' },
    { 'createdDate': '3/11/2016', 'createdBy': 'Bob' },
];

var occurrences = rows.reduce(function (acc, row) {
    acc[row.createdBy] = ++acc[row.createdBy] || 1;
    return acc;
}, {});

var result = Object.keys(occurrences).map(function (key) {
    return { key: key, value: occurrences[key] };
});

console.log(result);

Answer №2

This solution involves a single loop.

let dataList = [{ date: "7/11/2018", user: "Alice" }, { date: "7/12/2018", user: "Bob" }, { date: "7/12/2018", user: "Alice" }, { date: "7/13/2018", user: "Charlie" }, { date: "7/11/2018", user: "Alice" }],
    organizeData = function (data) {
        let result = [], obj = {};
        data.forEach(function (item) {
            if (!obj[item.user]) {
                obj[item.user] = { key: item.user, count: 0 };
                result.push(obj[item.user]);
            }
            obj[item.user].count++;
        });
        return result;
    }(dataList);

document.write('<pre>' + JSON.stringify(organizeData, 0, 4) + '</pre>');

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

Adjust THREE.PerspectiveCamera's distance without altering its viewing orientation

I have a PerspectiveCamera in THREE.js positioned somewhere in space as a child of a mesh. The camera is currently looking at the mesh with local coordinates [0, 0, 0]. I am looking for a way to change the distance of the camera from the mesh without chang ...

Python Script Completed with Error Messages from Crawling

I'm having trouble extracting room price and availability data from Expedia through their API. The issue arises when a hotel has no rooms available on a specific day, causing error messages to appear. The error message that appears when I use Print J ...

Customizing valueAxis dynamically in Amcharts

I am currently utilizing Amcharts to display my data. Within my chart, I have 4 graphs with valueAxes ranging from 0 to 100. Is there a method for me to dynamically change the valueAxes to a range of 0-250 after the chart has been loaded in the view? I ...

The functionality of jQuery on dropdown list change seems to be malfunctioning in Codeigniter

As a novice in CodeIgniter, I've scoured various StackOverflow threads for a solution to my issue without any luck. Below is the view code causing trouble: <select name="select1" id="select1"> <option value="0">None</option> ...

Accessing a child component's method within a parent component by making a call to it

I am facing an issue where I need to invoke a method in a child component from its parent component. Here is the specific scenario: Parent Component Example // ParentComponent.js class ParentComponent extends Component { render() { ret ...

Turn off all page scrolling on website

Is there a way to completely eliminate scrolling on a webpage? Currently, I have implemented the following CSS: html, body { overflow:hidden; } However, this solution does not effectively disable scrolling on iOS devices. In fact, it still allows scroll ...

Customize your Shopify Messenger icon using JavaScript!

Shopify recently introduced a new feature that allows customers to contact store owners through messenger. My client has requested me to customize the appearance of this icon with their branded icon instead. https://i.stack.imgur.com/uytpd.png I have not ...

Steer clear from using the implicit 'any' type while utilizing Object.keys in Typescript

I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature". Despite extensive discussion ...

Creating custom elements for the header bar in Ionic can easily be accomplished by adding your own unique design elements to the header bar or

I'm a beginner with Ionic and I'm looking to customize the items on the header bar. It appears that the header bar is created by the framework within the ion-nav-bar element. <ion-nav-bar class="bar-positive"> <ion-nav-back-button> ...

An effective method for retrieving the version from package.json

I am currently in the process of developing an SDK that will soon be available on npm. One of the requirements for this SDK is to deliver its version to the client. My goal is to have this version match the one specified in the package.json file. However ...

Utilizing JavaScript to trigger the :hover pseudo-class and implement event transfers

Consider this situation: You have a scenario where two images are stacked on top of each other. The image with the highest z-index is transparent and handles click events, similar to Google's Map API, while the image below is for visual representatio ...

What is the process behind executing the scripts in the jQuery GitHub repository when running "npm run build"?

Check out the jQuery repository on GitHub. Within the jQuery repo, there is a "build" folder. The readme.md mentions the npm command: npm run build This command triggers the execution of scripts in the build folder to complete the building process from ...

Disable the function when the mouse is moved off or released

My custom scrolling implementation in a ticker using Jquery is due to the fact that standard scrolling doesn't function well with existing CSS animations. The goal is to enable movement of the ticker when clicking and dragging on the controller, a div ...

Why is My TensorFlow.js Model for Predicting 2 Table Multiples Not Producing Accurate Results?

I have created a tensorflow.js model that predicts outputs in multiples of two. For example, if the input is 16, the prediction should be 32. However, even after providing the input data and labels accordingly, the output printed is [[1],] after prediction ...

Why is my react-hook-form sending an array with no data when making an axios request?

Within a container, I have mui Chips that contain labels. The objective is to utilize these chips as selectors, using onClick to add the label values to a list that will be sent in an Axios request. This needs to be achieved without the use of a textfield, ...

An error message pops up when using Next.js with Sass, indicating that a suitable loader is required to handle this file type

I've been struggling to properly wire up my next.js project with SCSS, but no matter what I try, it just won't work. I double-checked my setup for compiling SCSS files, but the error message keeps popping up: /scss/style.scss 1:0 Module parse f ...

Transmit the bound data (using ng-model) to a custom AngularJS directive

/*I am looking to define the maxDate as vmEndDate*/ app.directive('myDatepicker', function ($parse) { return function (scope, element, attrs, controller) { var ngModel = $parse(attrs.ngModel); alert(element.va ...

What is the best way to simulate a REST server with several endpoints within a single test in Java?

I need to validate a Java method that sends a request to an external REST server, retrieves JSON data, extracts an ID from the response, and then uses that ID to make another request to a different endpoint on the same server. While I have successfully us ...

How can we make a checkbox in React automatically checked based on the value in an object?

The checkbox function is functioning properly, updating the selected input value into this.state = { answers: [] };. However, the checkboxes are not displayed as selected on page load when the page is loading with this.state = { answers: [ { ...

Exploring the concept of multiple inheritance using ES6 classes

My research on this topic has been primarily focused on BabelJS and MDN. However, I acknowledge that there may be more information out there regarding the ES6 Spec that I have not yet explored. I am curious about whether ES6 supports multiple inheritance ...