Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this-

[
  {
    "id": "7",
    "name": "xyz",
    "job": "doctor",
    "preference": "1"
  },
  ...
]

My goal is to convert this array into a JSON object structure as follows-

[
  {
    "id": "7",
    "name": "xyz",
    "array1": [
      {
        "date": "today's Date,",
        "endDate": "somedate",
        "lastUpdatedBy": "someuser",
        "array2": [
          {
            "job": "doctor",
            "preference": "1"
          },
          ...
        ]
      }
    ]
   }
]

I am struggling to achieve this transformation using map or arrays nesting due to the challenge of avoiding duplicate keys for the same id and name combination. Your assistance in tackling this issue would be highly appreciated.

Below is a snippet of the code I have been attempting to modify:

let object = {
        id: data[i].id,
        name: data[i].name,
        array1:[ 
          {
          date: dateParam,
          endDate: '',
          lastUpdatedBy: 'me',
          array2: [
            {
            job: data[i].job,
            preference: data[i].preference
          }
        ]
        }
      ]
      };

Answer №1

I suggest breaking this down into two separate steps:

  1. First, group the items using id + name as the key
  2. Next, transform the grouped structure to achieve the desired output

For a practical demonstration, visit this live sandbox

Here is the code snippet for reference:


function groupBy<T, TKey>(list: T[], keyGetter: (arg: T) => TKey) {
  const map = new Map<TKey, T[]>();
  list.forEach((item) => {
    const key = keyGetter(item);
    const collection = map.get(key);
    if (!collection) {
      map.set(key, [item]);
    } else {
      collection.push(item);
    }
  });
  return map;
}

const groupedInput = groupBy(input, (x) => x.id + x.name);

const output = Array.from(groupedInput.entries()).map(([key, value]) => ({
  id: value[0].id,
  name: value[0].name,
  array1: value.map((x) => ({ job: x.job, preference: x.preference }))
}));

console.log(output);

To use it with your provided data, consider the following:

const input = [
  {
    id: "7",
    name: "xyz",
    job: "doctor",
    preference: "1"
  },
  {
    id: "7",
    name: "xyz",
    job: "nurse",
    preference: "2"
  },
  // Additional data entries here
];

The expected output will be structured like this:


[{
        "id": "7",
        "name": "xyz",
        "array1": [{
                "job": "doctor",
                "preference": "1"
            }, 
            // Additional mapped entries here
        ]
    }
]

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

Converting an array of ByteArray into a MemoryStream

There is a method in my code that returns an array of ByteArray: public byte[][] GenerateImage(ImageFormat format, ImageSize size); I want to store this array into a MemoryStream: var imageArray = instanceName.GenerateImage(ImageFormat.Jpeg, ImageSize.D ...

React app's compilation is failing due to non-compliant ES5 code generation of the abab module, resulting in errors on IE

Can anyone explain why a create-react-app project using TypeScript and configured to generate ES5 code is not functioning on IE11 due to the "atob" function from the 'abab' package not being compiled into ES5 compliant code? module.exports = { ...

Is there a way to use jQuery to enable multiple checkboxes without assigning individual IDs to each one?

I need help finding a way to efficiently select multiple checkboxes using jQuery without relying on individual ids. All of my checkboxes are organized in a consistent grouping, making it easier for me to target them collectively. To illustrate my issue, I ...

What is the method for including a class in the anchor element that is the closest sibling of the containing ul element in the HTML structure?

I'm currently exploring traversal in jQuery and I'm a bit confused about how the class is being added to all the items in the unordered list. I know it's probably something simple that I'm missing. Any assistance would be greatly apprec ...

Executing Angular2 application within Docker container

I have created a Docker file to run my ng2 app in a container: FROM ubuntu:latest RUN apt-get update #Install curl & git RUN apt-get -qq -y install curl RUN apt-get install -yqq git #Download and install nodejs-6 RUN curl -sL https://deb.nodesourc ...

Determine the presence of a Facebook user by using JavaScript

I am trying to find a method to verify the existence of a Facebook user based on their ID. As far as I understand, there is a Graph API that can provide a Facebook user's profile picture using their ID in this format: I have noticed that if an inval ...

Typescript's intriguing concept of objects containing arrays inside other objects

I have a structure similar to this and I am trying to create definitions for types/interfaces, but I am facing issues in making it work correctly. layoutsSet: { 1: { "lg": [ { i: "1", x: 0, ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

What is the best way to present a unique page overlay specifically for iPhone users?

When browsing WebMD on a computer, you'll see one page. However, if you access it from an iPhone, not only will you be directed to their mobile page (which is easy enough), but they also display a special overlay with a "click to close" button prompti ...

When an empty array is returned from a catch statement in an async/await method, TypeScript infers it as never

Function getData() returns a Promise<Output[]>. When used without a catch statement, the inferred data type is Output[]. However, adding a catch statement in front of the getData() method changes the inferred data type to Output[] | void. This sugge ...

Tips for mapping complex JSON structures to Java objects with the Jackson API

Looking to create a JAVA code utilizing JACKSON that can showcase a complex hierarchy in JSON format, subject to conditions based on "validFrom" and "validTo" parameters. In this example, the dates for "validFrom" and "validTo" are uniform. However, in re ...

Issue: $injector:unpr Unknown Provider (app.js is appearing to be properly defined)

Struggling with the unknown provider issue, I've searched through other threads and tried their solutions to no avail. My goal is to inject 'MockSvc' service into a controller without encountering any errors. Any advice would be greatly appr ...

How to serialize a subclass using Json.NET

When attempting to utilize Json.NET for serializing a subclass, I noticed that the resulting JSON only contains properties from the superclass and not the subclass object itself. This issue seems similar to one discussed in this Stack Overflow thread, but ...

Is there an easy method for importing, modifying and saving JSON files?

I am encountering issues with editing a JSON file and saving the changes in a usable format. The starting point for my problem is: modify-json-file-using-some-condition-and-create-new-json-file-in-r Even though I am attempting something simpler, it still ...

Conceal elements and offspring in D3.js through the utilization of JavaScript or jQuery

I am currently customizing a fantastic force directed layout created by @eyaler (http://bl.ocks.org/eyaler/1058611) that offers multiple options. My goal is to conceal a specific node with its children using jQuery or D3 along with JavaScript, not directly ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

Is it possible to utilize the map method to extract objects that are nested multiple layers deep?

I am working on accessing the change order information in order to compile a list of all the change_order_names. The code I am currently using is yielding the results displayed below. Could someone assist me in understanding how to access the change order ...

Toggle the hamburger menu using JavaScript

How can I close my hamburger menu when clicking a link for one page navigation? The menu is functioning properly, but I need a way to close it. Unfortunately, I have limited knowledge of JS. I only have the HTML and CSS for this: HTML in index.html file ...

Using Volley to display a ListView

I am attempting to establish a connection between SQL Server and Android Studio using JSON with the code provided below. While I do not encounter any errors in Android Studio, testing the application on my phone results in an "Error in connection" message. ...

Creating a server that is exclusive to the application in Node.js/npm or altering the response body of outgoing requests

As I work on developing a node app, the need for a server that can be used internally by the app has become apparent. In my attempts to create a server without listening to a port, I have hit a roadblock where further actions seem impossible: let http = ...