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

Conceal the React button once it has been pressed

In my checklist of questions, I have set up a system where the first button is shown if any checkboxes are selected. If no checkbox is selected, then the second "Submit" button is displayed. Upon clicking submit, a message appears inside. Additionally, for ...

What is the recommended return type in Typescript for a component that returns a Material-UI TableContainer?

My component is generating a Material-UI Table wrapped inside a TableContainer const DataReleaseChart = (): React.FC<?> => { return ( <TableContainer sx={{ display: 'grid', rowGap: 7, }} > ...

Combining data types to create a unified set of keys found within a complex nested structure

This problem is really testing my patience. No matter what I do, I just can't seem to make it work properly. Here's the closest I've come so far: // Defining a complex type type O = Record<'a', Record<'b' | 'x& ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Using MappingJacksonValue with Spring Boot for JSONP response and handling strict MIME type errors

After extensively researching JSONP support with Spring 4, I am still struggling to find a straightforward explanation on how to make it work with the correct media type in Chrome. 1) I implemented the JsonpAdvice following the guidelines from Jackson JSO ...

A guide to swapping text in a jQuery DOM component

In order to construct HTML from a jQuery ajax response, I prefer not to nest unsightly strings in javascript and avoid using templating scripts like mustache. Instead, I decided to utilize a template HTML with display: none as shown below: <div id="mes ...

Vue's intelligent element loading feature ensures that elements that are not displayed are delayed

My Vue gallery component includes a lightbox feature defined by the following code: <div id="lightbox" class="modal" v-if="photo !== null" v-show="showModal" @click.self="closeModal"> <div clas ...

The state is failing to initiate a re-render despite a change in its state

In my React application, I have encountered an issue with combining two reducers. One of the reducers is functioning properly, but the other one is not triggering a re-render after a state change. Interestingly, when I save a document or make a change in t ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...

Utilizing AngularJS and ADAL.JS to Define Resource ID (Audience)

Is there a way to utilize adal.js within AngularJS to obtain a bearer token for the audience https://management.azure.com through JavaScript? I have created a client application in Azure AD and configured its permissions to allow access to the "Windows Az ...

When I test my jQuery scripts in jsfiddle, they run smoothly. However, they do not seem to work properly when I

My code is almost perfect, but the jQuery function is giving me trouble. It works fine in jsfiddle, but for some reason, it's not functioning in my HTML file. I don't believe extra characters are being added when copying from the HTML file. I hav ...

The partition.nodes(root) function in d3.js does not assign values to the x or dx properties of the nodes

I am currently experimenting with d3.js to create a unique icicle tree visualization using data sourced from a .json file. The challenge I'm facing lies in the fact that the x and dx attributes of the partition nodes are consistently being set to 0. M ...

Initial position of jQuery slider

A while back, I came across some slider code on a website and copied it. Unfortunately, I can't seem to locate the source now. Here is the code snippet: slides.min.jquery.js $(function(){ $('#slides').slides({ preload: true, ...

What are the steps to generating and sharing 'npm create' scripts?

I am looking to develop and release a script on npm that functions similarly to: npm create qwik@latest or yarn create next-app --typescript However, I am unsure where to begin. Despite searching extensively online, I have not been able to find any helpf ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

Sinon - observing the constructor function

While I've come across a few related inquiries, none seem to address what I am specifically looking to achieve. My goal is to monitor a constructor method in such a way that when an object created with the constructor calls this method from a differe ...

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...

animations are not triggering when using ng-click inside ng-repeat, is there a reason why the event is not firing?

Check out the code in jsFiddler here After reviewing the code, it's clear that when the add button is clicked, a new item is pushed to the $scope.p. Each item in the ng-repeat loop has an event-binding and everything functions correctly. However, onc ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...