divide the JSON object into distinct indexes

Below is an array containing JSON objects:

items = [
         {
           id: '1',
           name: 'Josh',
           transactionDate: '2012-08-10',
           creditAmount: '200',
           numberBank: '12345',
         },
         {
           id: '1',
           name: 'Josh',
           transactionDate: '2012-08-14',
           creditAmount: '159',
           numberBank: '12345',
         },
         {
           id: '1',
           name: 'Josh',
           transactionDate: '2012-08-15',
           creditAmount: '3421',
           numberBank: '12345',
         },
         {
           id: '2',
           name: 'George',
           transactionDate: '2012-09-15',
           creditAmount: '6000',
           numberBank: '13345',
         },
         {
           id: '2',
           name: 'George',
           transactionDate: '2012-09-16',
           creditAmount: '6565',
           numberBank: '13345',
         }
        ]

I need to group the array by the same id:

For example:

        [
         {
           id: '1',
           name: 'Josh',
           transactionDate: '2012-08-10',
           creditAmount: '200',
           numberBank: '12345',
         },
         {
           id: '1',
           name: 'Josh',
           transactionDate: '2012-08-14',
           creditAmount: '159',
           numberBank: '12345',
         },
         {
           id: '1',
           name: 'Josh',
           transactionDate: '2012-08-15',
           creditAmount: '3421',
           numberBank: '12345',
         }
        ],
        [
         {
           id: '2',
           name: 'George',
           transactionDate: '2012-09-15',
           creditAmount: '6000',
           numberBank: '13345',
         },
         {
           id: '2',
           name: 'George',
           transactionDate: '2012-09-16',
           creditAmount: '6565',
           numberBank: '13345',
         }
        ]

Is there any way to achieve this? Thank you.

Answer №1

Using the reduce function to group by id and then extract the values of the resulting object with Object.values
MORE INFO
??= represents the logical nullish assignment. The right side value is assigned when the left side is null or undefined.

let items = [         {           id: '1',           name: 'Josh',           transactionDate: '2012-08-10',           creditAmount: '200',           numberBank: '12345',         },         {           id: '1',           name: 'Josh',           transactionDate: '2012-08-14',           creditAmount: '159',           numberBank: '12345',         },         {           id: '1',           name: 'Josh',           transactionDate: '2012-08-15',           creditAmount: '3421',           numberBank: '12345',         },         {           id: '2',           name: 'George',           transactionDate: '2012-09-15',           creditAmount: '6000',           numberBank: '13345',         },         {           id: '2',           name: 'George',           transactionDate: '2012-09-16',           creditAmount: '6565',           numberBank: '13345',         }        ]
        
const res = Object.values(items.reduce((acc,curr)=> {
  acc[curr.id]??=[]  //equivalent to acc[curr.id] = acc[curr.id] || [] in this situation
  acc[curr.id].push(curr)
  return acc
},{}))

console.log(res)

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 jQuery centering in IE browsers with jquery-ui-1.10.3.custom.js and jquery-ui-1.9.2.custom.js not working as expected

Are there any other alternatives you can recommend? Here is the dialog structure: <div id="dialogbox" title="message box"> <p>example content</P> </div> ...

How can CORS be activated? Is it through the server or Javascript, and where does this

Currently, I am testing my ReactJS website on localhost:3333 and my ASP.NET Web API 2 on localhost:54690. I am utilizing axios for my AJAX requests, but encountering an error when making a request. XMLHttpRequest cannot load http://localhost:54690/api/ ...

The append method is not available for a div element

this is my unique code snippet for (i = 0 ; i< number ; i++){ var iDiv = document.createElement('div'); iDiv.innerHTML = "<label for=\"timeslot\" class=\"p-label-required\">Time Slot</label>" iDiv.i ...

Issue with JavaScript Variable Not Reflecting Changes in Progress Bar

I'm in the midst of developing a game and have incorporated a progress bar to facilitate the incrementation of certain values on my HTML page. However, once the progress bar hits 100%, it updates the cost and level only once. After that initial update ...

Manipulate JSON values within a JSON array in Java

{ "page": { "size": 2, "number": 2 }, "places": [ { "eventName": "XYZ", "createdByUser": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

What is the method for generating a binary numpy array with two columns from a list of strings?

Input: A list of strings provided below: ['x', 'x', 'y', 'z', 'z', 'x', 'y'] Desired Output: I am looking to convert this list into a numpy array as shown: array([[ 1, 0, 0], ...

What does the error message "Uncaught TypeError: Cannot access property 'style' of an undefined object" mean?

I've been attempting to execute the code below, but I keep encountering an error. I even tried including document.addEventListener('DOMContentLoaded', (event) => yet it still doesn't work. Interestingly, there are no errors if I run ...

Converting JSON data into a JavaScript array and storing it in a variable

Currently, I am delving into the world of JavaScript and my instructor has assigned a task that involves utilizing information from a JSON file within our JavaScript code. The issue I'm facing is deciphering how to effectively convert the JSON data i ...

Convert a string with the characters '"' retrieved from a MySQL database into JSON

After creating a JSON object and storing it in MySQL, I encountered an issue when trying to retrieve and parse it. When I stringify the JSON object, the properties are being enclosed in double quotes causing issues when parsing the retrieved string. Below ...

Showing Text Information from a distant web server's jQuery.getJSON() script

I am currently working on a personal project that involves displaying data from a remote server. The HTML code I am using looks like this: <script> jQuery.getJSON("http://someurl.com/something.cgi? AJZ=1&STOCK=S", function(data) { if (data.inform ...

Adjusting height in Google Maps to fill the remaining space

Currently, I am developing a map application where I want the Google Maps DIV to occupy the remaining height under the header. Here is the code snippet: <!DOCTYPE html> <head> <title>Map Application</title> <style type ...

"Is it possible to send JSON data as bytes to a websocket server using Flutter

My task involves creating a JSON message in Dart language to be sent to a websocket server. The server only accepts properly formatted JSON requests and will refuse connection for plain text or incorrect formats. The initial JSON message creation function ...

Issues with npm installation on Ubuntu 16.04

Encountering issues while attempting to install npm on Ubuntu 16.04 using the command sudo apt-get install npm. The errors received are as follows: The following packages have unmet dependencies: npm : Depends: nodejs but it is not going to be installed ...

Creating a cube with unique textures on each face in three.js r81: What's the best way to achieve this?

After updating to the latest version of three.js, I encountered an issue where THREE.ImageUtils.loadTexture no longer works. As a result, I tried searching for examples of cubes with different faces, but they all utilized the outdated technique "new THREE. ...

Is it better to master JavaScript before diving into JQuery?

When diving into the world of JavaScript in 2012, is it more beneficial to start by learning JavaScript first and then move on to jQuery, or should one jump right into jQuery without prior knowledge of JavaScript? ...

What is the best way to expand a div in a downward direction exclusively?

My task involves a parent div containing a centered child div. My goal is to have the child div grow downwards only upon clicking it, not in both directions. Initial state of the two divs: https://i.sstatic.net/cWYyV.png Outcome after clicking on div 2: ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Tips for transferring and incorporating custom helper functions in JS/React

Task at Hand: Instead of constantly typing console, I want to import some shorthand. For example-- log('hi') should be the same as console.log('hi') Attempted Solution: This is what I have so far. I want to use shortcuts like l ...

The v-for directive on a reactive Vuejs array is failing to render its elements

After much searching, I have identified the error and provided a brief explanation in the following paragraph. The code below resolves the error by changing the approach of the code rather than fixing the error itself. By defining the indexes of the array ...

"Enable a smooth transition and switch the visibility of a div element when clicked

How to create a dropdown form with a transition effect that triggers on click of an element? Once triggered, the transition works smoothly but clicking again only hides the div element without triggering the transition. See the demo here: Check out the fu ...