Consolidate common values within a JSON object into a single grouping

Hello there, I need some help with grouping two JSON objects into a single array by common values.

Here is the initial input:

const json = {
   "2280492":[
      {
         "ID":"2280492",
         "Name":"Paula Luying",
         "Surname":"Domingo",
         "Estate":"End",
         "Date_End":"4/15/2021 12:31",
         "Date_final":"4/22/2021 13:57",
         "Time":"7 days 1 hours",
         "Note":"7.83"
      },
      {
         "ID":"2280492",
         "Name":"Paula Luying",
         "Surname":"Domingo",
         "Estate":"End",
         "Date_End":"4/22/2021 13:58",
         "Date_final":"4/23/2021 11:36",
         "Time":"21 hours 38 minutes",
         "Note":"0"
      }
   ],
   "2423536":[
      {
         "ID":"2423536",
         "Name":"Josep",
         "Surname":"Mora",
         "Estate":"Acabat",
         "Date_End":"4/19/2021 10:31",
         "Date_final":"4/19/2021 11:19",
         "Time":"48 minutes 33 seconds",
         "Note":"9"
      },
      {
         "ID":"2423536",
         "Name":"Josep",
         "Surname":"Mora",
         "Estate":"Acabat",
         "Date_End":"4/19/2021 11:20",
         "Date_final":"4/22/2021 22:43",
         "Time":"3 days 11 hours",
         "Note":"4.67"
      }
   ]
}

I want to transform this data into the following output format where common tags like "ID", "NAME,"Surname" are grouped and there is an additional tag called activities for unique data:

const json = [
   {
      "ID":"2280492",
      "Name":"Paula Luying",
      "Surname":"Domingo",
      "Activities":[
         {
            "Estate":"End",
            "Date_End":"4/15/2021 12:31",
            "Date_final":"4/22/2021 13:57",
            "Time":"7 days 1 hours",
            "Note":"7.83"
         },
         {
            "Estate":"End",
            "Date_End":"4/22/2021 13:58",
            "Date_final":"4/23/2021 11:36",
            "Time":"21 hours 38 minutes",
            "Note":"0"
         }
      ]
   },
   {
      "ID":"2423536",
      "Name":"Josep",
      "Surname":"Mora",
      "Activities":[
         {
            "Estate":"Acabat",
            "Date_End":"4/19/2021 10:31",
            "Date_final":"4/19/2021 11:19",
            "Time":"48 minutes 33 seconds",
            "Note":"9"
         },
         {
            "Date_End":"4/19/2021 11:20",
            "Date_final":"4/22/2021 22:43",
            "Time":"3 days 11 hours",
            "Note":"4.67"
         }
      ]
   }
]

Answer №1

Here is a sample code snippet that can help achieve the desired outcome:

const groupByIdNameSurname = (data) => Object.values(data.reduce((res, {
  ID,
  Name,
  Surname,
  ...rest
}) => {
  const Activities = res[ID]?.Activities || []
  res[ID] = {
    ID,
    Name,
    Surname,
    Activities: [...Activities, rest]
  }
  return res
}, {}))


const json = {
  "2280492": [{
      "ID": "2280492",
      "Name": "Paula Luying",
      "Surname": "Domingo",
      "Estate": "End",
      "Date_End": "4/15/2021 12:31",
      "Date_final": "4/22/2021 13:57",
      "Time": "7 days 1 hours",
      "Note": "7.83",
    },
    {
      "ID": "2280492",
      "Name": "Paula Luying",
      "Surname": "Domingo",
      "Estate": "End",
      "Date_End": "4/22/2021 13:58",
      "Date_final": "4/23/2021 11:36",
      "Time": "21 hours 38 minutes",
      "Note": "0",
    }
  ],
  "2423536": [{
      "ID": "2423536",
      "Name": "Josep",
      "Surname": "Mora",
      "Estate": "Acabat",
      "Date_End": "4/19/2021 10:31",
      "Date_final": "4/19/2021 11:19",
      "Time": "48 minutes 33 seconds",
      "Note": "9",
    },
    {
      "ID": "2423536",
      "Name": "Josep",
      "Surname": "Mora",
      "Estate": "Acabat",
      "Date_End": "4/19/2021 11:20",
      "Date_final": "4/22/2021 22:43",
      "Time": "3 days 11 hours",
      "Note": "4.67",
    }
  ]
}

console.log(groupByIdNameSurname(Object.values(json).flat()))

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

Adding a nested data structure in a Meteor application

In my mongo collection, I have a document named exam. // meteor:PRIMARY> db.exam.find() { "_id" : "RLvWTcsrbRXJeTqdB", "examschoolid" : "5FF2JRddZdtTHuwkx", "examsubjects" : [ { "subject" : "Z4eLrwGwqG4pw4HKX" }, ...

Getting the dimensions of an image when clicking on a link

Trying to retrieve width and height of an image from this link. <a id="CloudThumb_id_1" class="cloud-zoom-gallery" rel="useZoom: 'zoom1', smallImage: 'http://www.example.com/598441_l2.jpg'" onclick="return theFunction();" href="http ...

What's the best way to update the fill color of an SVG dynamically?

Is it possible to change the color of an SVG image dynamically without using inline SVG tags? I want to create a code that allows users to specify the source for the SVG tag and a hexadecimal color value, enabling them to customize any SVG image with their ...

Socket.io in Express is already assigned to another address

I'm having trouble getting my app to connect with Socket.io via websockets. Each time I attempt to run this code snippet, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 Despite checking for any other process ...

The request cannot be completed using GET. The connection has not been established, and the offline queue is not activated

Encountering this unexpected error in the live environment, despite implementing a retry strategy of 500ms and wrapping the setAsync and getAsync functions with a setTimeout of 1s. It's puzzling why this issue persists. Error Message: AbortError at ...

Adding Options on the Fly

I am struggling with integrating option elements into optgroups within my HTML structure using JavaScript, particularly while utilizing the jQuery Mobile framework. Below is the initial HTML setup: <form> <div class="ui-field-contain"> ...

Filtering a table using jQuery based on the class or data attributes

Issue arises when selecting the first "Icon" shows "Not found", then opting for "Talisman" does not display. It should show "Not Found". Is this achievable? Add the classes f-Icon, f-Ring, f-Neck. Then search for the value by class. Select either "Icon R ...

Backend communication functions seamlessly within the service scope, yet encounters obstacles beyond the service boundaries

I'm facing an issue with accessing data from my backend. Although the service successfully retrieves and logs the data, when I try to use that service in a different module, it either shows "undefined" or "Observable". Does anyone have any suggestions ...

Tips for transforming information into JSON format

Imagine having a file with data in CSV or TXT format, such as: Name, Surname, Age, Occupation Gino, DiNanni, 19, Student Anna, Kournikova, 27, Programmer (Extra spaces have been added to enhance readability) The goal ...

The XMLHttpRequest response states that the preflight request did not meet the access control check requirements

I am attempting to subscribe to a firebase cloud messaging topic by sending an http post request. var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState ...

How to fill an HTML template using ngFor without using a JSON array

Is there a way to fill the HTML with basic JSON like below: { "id": 34, "name": "Tip 33", "description": "Tip description 33", "created_at": "2018-01-26 18:59:19", "updated_at": "2018-01-26 18:59:19" } The code i tried using was: < ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

What is the best way to arrange an array using AngularJs or Javascript?

When a user makes a selection, I want to sort and display an array in alphabetical order. Specifically, when we render data from the backend, I would like to display the fullName in alphabetical order. The $scope.selectedControlOwner is the ng-click event ...

Contrast among 17-digit timestamps

Currently, I am dealing with timestamps in Node.js that are in the UTC+02:00 timezone. I am trying to calculate the time difference between two timestamps, each consisting of 17 digits. For instance, I have two timestamps: 20180712080000000 (YYYYMMDDHHmmss ...

Obtain data from JSON by leveraging Ansible's map functionality

I am trying to extract the UserId from the following output: ok: [localhost] => {"ansible_facts": {"Usernamelis": "", "_raw_params": "\"{u'Users': [{u'UserName': u'reo', u'PasswordLastUsed': u'201 ...

Is there an issue with retrieving JSON data in Swift 4?

Having an issue with parsing a weather forecast JSON using the new Swift 4 method for serializing JSON with structure. Whenever I try to print the JSON, I get the following error message: typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: ...

Preserving the information from a webpage by utilizing casperjs for scraping and saving table data

What is the most efficient way to preserve table data collected during a web scraping process with casperjs? Saving it as a file after serializing into a json object. Sending an ajax request to php and then storing it in a mysql database. ...

Guide for implementing smooth fade in and out effect for toggling text with button click

I have this code snippet that toggles text on button click: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function toggleText(){ ...

Having trouble showing JSON data in a Swift TableView

Having trouble displaying a JSON array in a TableView? The table appears blank, even though it works with fixed data. I can parse the JSON and manipulate the console output, so the issue might be with the reload table function. I've tried various solu ...

How can I configure Grails to properly interpret my JSON PUT AJAX request?

In this Grails app, the form is set up in a standard way. <g:form url="[resource:myClass, action:'update']" method="PUT" > <fieldset class="form"> <g:render template="form"/> </fieldset> <fieldset c ...