Merge the values into an array based on their shared id within a JSON object

Is it possible to map JSON objects with duplicate id values to their association property in an array using JavaScript after a join operation?

{
    "id": 1,
    "name": "doc 1",
    "appointmentTime": "2018-12-28T00:00:43"
},

{
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-25T23:00:53"
},
{
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-26T23:00:02"
},
{
    "id": 3,
    "name": "doc3",
    "appointmentTime": null
},

Desired output:

{
    "id": 1,
    "name": "doc1",
    "appointmentTime": ["2018-12-28T00:00:43"]
},
{
        "id": 2,
        "name": "doc 2",
        "appointmentTime": ["2018-12-26T23:00:02","2018-12-26T23:00:02"]
    },
    {
        "id": 3,
        "name": "doc3",
        "appointmentTime": null
    },

Answer №1

To accomplish this task, you should utilize the reduce function:

const data = [{
    "id": 1,
    "name": "document 1",
    "createdTime": "2018-12-28T00:00:43"
},

{
    "id": 2,
    "name": "document 2",
    "createdTime": "2018-12-25T23:00:53"
},
{
    "id": 2,
    "name": "document 2",
    "createdTime": "2018-12-26T23:00:02"
},
{
    "id": 3,
    "name": "document 3",
    "createdTime": null
}]

const output = data.reduce((acc, {id, name, createdTime}) => {
  const found = acc.find(item => item.id === id)
  if (found) { found.createdTime.push(createdTime) } 
  else {acc.push({id, name, createdTime: [createdTime]})}
  
  return acc
}, [])

console.log(output)

I have also incorporated the destructuring assignment

Answer №2

> const combineDuplicates = (arr, key, mergeKey) => {
>     const hashMap = {}; 
>     arr.forEach(item => {
>         if(hashMap[item[key]] === null) { 
>             item[mergeKey] = [item[mergeKey]]; 
>             hashMap[item[key]] = item;  
>         }
>         else { 
>             hashMap[item[key]][mergeKey].push(item[mergeKey]); 
>         }
>
>         const combinedArr = [];
>         for(let uniqueKey in hashMap) {
>             combinedArr.push(hashMap[uniqueKey]);
>         }
>         return combinedArr;
>     });
> }
> updatedArray = combineDuplicates(updatedArray, "identifier", "timeOfEvent");

Answer №3

This is my approach:

    //Assuming you have jsonObj stored in an Array like this:
var myarray = [{
    "id": 1,
    "name": "doc 1",
    "appointmentTime": "2018-12-28T00:00:43"
  },
  {
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-25T23:00:53"
  },
  {
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-26T23:00:02"
  },
  {
    "id": 3,
    "name": "doc3",
    "appointmentTime": null
  }
];

//Iterate through the data to combine duplicates
for (var i = 0; i < myarray.length; i++) {
  //Check for duplicate data
  for (var j = i + 1; j < myarray.length; j++) {
    if (myarray[i].id == myarray[j].id) {
      var tmp = myarray[j].appointmentTime;
      myarray[j].appointmentTime = [];
      myarray[j].appointmentTime.push(tmp);
      myarray[j].appointmentTime.push(myarray[i].appointmentTime);

      myarray[i] = {};
    }
  }
}
console.log(myarray);

Finally, remove any empty JSON objects.

https://jsfiddle.net/m073qwr6/1/

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

Is there a way to shorten the length by left-clicking and increase it by right-clicking?

Illustration: section.my{margin: 20px;} <section class="my"></section> Hover over: section{padding: 10px;} Double click: section{border: 1px solid black;} ...

What steps should I follow to parse this JSON in Java? My objective is to retrieve the specific details of a keypad with an ID of 1. Can you guide me on how to

{ "Pump Details": { "Pump Configuration": "DUO", "Keypad": [{ "Keypad AssetID ": 0, "Keypad SHASignature": null, "KeyPad Software Version": null, "Keypad CheckSum": null, "Ke ...

NodeJS buffer is not capable of handling incomplete TCP stream data

While troubleshooting my TCP JSON stream on the live server, I discovered that if the data streamed to me in JSON format is excessive, it doesn't consistently parse correctly. It requires multiple streams for successful parsing. Here is the code I am ...

Creating a custom toJSON function for a property declared using Object.defineProperty

Let's consider a scenario where we have an object with a specific property that is meant to reference another object, as shown below: Object.defineProperty(parent, 'child', { enumerable: true, get: function() { return this._actualCh ...

What are some ways to incorporate texture into objects using three.js?

Having trouble adding texture to my central sphere (earth) without the object disappearing. Can someone provide guidance on where I might be making a mistake? Your help is appreciated. For reference, here is the link to my jsbin http://jsbin.com/cabape/edi ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

Difficulty displaying API information on a web browser with react.js

I am currently working on developing a trivia game using React.js Typescript and The Trivia API. I have been successfully passing data between components with useContext and navigating through components using react-router-dom. However, I encountered an is ...

Using JavaScript to trigger an event when there is a change in the innerHTML or attributes

I have come across a jQuery calendar with the capability to scroll through months, and I am interested in triggering an event each time the month changes so that I can assign event listeners to every td element within the table (with days represented by ...

Error: Phonegap displaying incomplete or corrupted image

Currently, my Android application is being developed with Phonegap. Users have the ability to take photos that are then stored in a mysql database (medium-blob column) using a simple INSERT INTO query without altering the data. These images are then sent s ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

Issues with ng-click functionality not activating on <li> HTML elements

I've been attempting to add ng-click functionality to my list, but it's not working as expected. I've tried adding the ng-repeat directive and also without it on li elements. Here is the snippet of HTML code: <ul class="nav nav-tabs"&g ...

What is the best way to transfer JavaScript if conditions to an external file?

I am currently working on a script to transfer data between various software applications. Within this script, there is an if condition set up to ignore specific fields that are not required for the transfer process. The condition in question looks somethi ...

Build a Search Suggestions feature with Node Package Manager (NPM) and Model-View-Controller (M

Stepping into the exciting world of MVC core and harnessing NPM for JavaScript packages has been a learning curve. However, I've encountered an issue that requires some deliberation on the best course of action for resolution. To provide context, I ha ...

My picture is refusing to load... Why does it keep saying "image not found"? Any thoughts on why this might be

I've been trying to display a picture of myself on my html canvas, the image is stored in the correct folder. However, I keep encountering a strange error (shown above) and I can't seem to figure out what's causing it. If you have any insigh ...

I encountered an error in the console stating, "Uncaught ReferenceError: req is not defined," while trying to access req.query.id

Encountering the error 'Uncaught ReferenceError: req is not defined' when attempting to use req.query.id. Below is the content of my index.js file: const express = require("express"); const path = require("path"); const port = 8000; ...

JavaScript can be used to target and remove parent <tr> elements that contain empty <td> elements with a specific class

I am facing a challenge with a large HTML table that is populated by variables set in JavaScript from my database response. When the database returns an empty string, I want to remove the entire parent row using JavaScript. Although I have attempted to us ...

Incorporating a MUI5 theme into a custom emotion-themed application

I'm currently working on an application that incorporates multiple themes. One of these is a Material UI theme specifically designed for MUI v4, while the other is an emotion theme used by non-MUI components. In my attempt to transition to MUI v5, I ...

I am struggling to retrieve a value from the angular.forEach function, the flag value is not being obtained. What could be

I'm having an issue with my controller.js file. I can't seem to access the value from the angular.forEach function, specifically the flagvalue isn't being retrieved. Is it because the scope of flagvalue ends when the forEach function complet ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Using jQuery, prevent the user from entering text into an input box when a checkbox

In my project, there is a checkbox that determines whether an input box is disabled. The issue arises when I try to disable the input based on the database value. For example, when the value is 0, it should display as disabled false; however, the input rem ...