Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated.

The current representation of individual's data needs to be revised to group individuals by department.

Here is the existing response:

    {
   "statusCode":200,
   "message":"OK",
   "status":"success",
   "response":{
      "data":[
         {
            "name":"John",
            "age":30,
            "department":"Hardware"
         },
         {
            "name":"Durai",
            "age":22,
            "department":"Hardware"
         },
         {
            "name":"Durai",
            "age":22,
            "department":"Software"
         },
         {
            "name":"Durai",
            "age":22,
            "department":"Software"
          }
      ]
   }
}

The desired response format is as follows:

    {
   "statusCode":200,
   "message":"OK",
   "status":"success",
   "response":{
      "data":{
         "department":"Hardware",
         "persons":[
            {
               "name":"John",
               "age":30,
               "department":"Hardware"
            },
            {
               "name":"Durai",
               "age":22,
               "department":"Hardware"
            }
         ]
      },
      "department":"Hardware",
      "persons":[
         {
            "name":"Durai",
            "age":22,
           "department":"Software"
         },
         {
            "name":"Durai",
            "age":22,
            "department":"Software"
         }
      ]
   }
}

Answer №1

Here's a potential solution to tackle this problem...

const originalInfo = [{
    "name": "Sarah",
    "age": 25,
    "department": "Marketing"
  },
  {
    "name": "Mike",
    "age": 35,
    "department": "Sales"
  },
  {
    "name": "Jane",
    "age": 28,
    "department": "Marketing"
  },
  {
    "name": "David",
    "age": 33,
    "department": "Sales"
  }
]

let updatedInfo = [];
originalInfo.forEach(item => {
// Determine if there is already an entry for this department...
  if (updatedInfo.filter(item2 => item2.department == item.department).length == 0) {
  // If not, create a new entry and initialize the employees array
    updatedInfo.push({
      department: item.department,
      employees: [item]
    })
  } else {
  // If yes, locate it and include another employee
    updatedInfo.forEach(entry => {
      if (entry.department == item.department) entry.employees.push(item);
    })
  }
})

console.log(updatedInfo)

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

The process of efficiently uploading a batch of images to Firebase storage while also obtaining all the respective

I have been using firebase storage to upload images and save their respective URLs in the firebase database. However, I recently encountered an issue with my code. In firebase v8, everything was working fine, but after updating to version 9, the following ...

Unveiling Fresh URLs within an iFrame

Here is the current situation: www.mywebsite.com/Pagex.html - On this page, there is an iFrame with a default URL (src) from a different domain than the host page (Pagex.html). The code inside the iFrame is a user input form with a submit button. Upon su ...

Is there a way to position the Image component from next/image using absolute positioning?

Is it possible to use an element Image from 'next/image' with the CSS style { position: absolute; left: 50% }? It appears that it is not being applied. For example: import React from 'react' import Image from 'next/image' imp ...

Is it possible for you to enter "1.00" instead of just 1 when using the input type as number?

I am using Polymer paper-input and I would like to ensure that my input with type "number" always displays 2 decimal points, even when it is a whole number. Instead of just displaying as "1", I want it to be shown as "1.00" at all times. I have tried sett ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

passing JSON data using JavaScript or jQuery

I have a JSON snippet that I need to parse using JavaScript or jQuery and convert into variables: name and meetup. Can you help me with this? Below is the JSON code: { "MYID": 1, "module": [ { "name": "Manchester", ...

Running the application through Jenkins by using the command npm start

Running shell commands npm start & is giving us some trouble. Our Jenkins jobs seem to either run endlessly or npm doesn't start properly. We're wondering what the best approach would be, especially when needing to start multiple nodejs s ...

Transform the page into a Matrix-inspired design

I decided to transform the appearance of my web pages into a stylish The Matrix theme on Google Chrome, specifically for improved readability in night mode. To achieve this goal, I embarked on the journey of developing a custom Google Chrome extension. The ...

What is the best way to showcase nested array JSON data in an HTML Table?

https://i.stack.imgur.com/OHL0A.png I attempted to access the following link http://jsfiddle.net/jlspake/v2L1ny8r/7/ but without any success. This is my TypeScript code: var viewModel = function(data){ var self = this; self.orders = ko.observableArr ...

Using AngularJS Material's mdDialog to show locally stored data in a template

In the controller, the section responsible for spawning mdDialog appears as follows: $scope.removeAttendee = function(item) { console.log(item); $mdDialog.show({ controller: DialogController, templateUrl: 'views/removeMsg.tm ...

Dealing with Angular package.json and unresolved peer dependencies

As I embark on the journey of developing an Angular project using CLI, I am also exploring additional components like angular handsontable and primeng. Amidst this exploration, a wave of confusion hit me when I attempted to check the versions of various pa ...

What could be causing the issue with res.download() function not functioning properly while passing a file path?

Hey there! I'm working on a cool project that involves allowing users to input a file path and then download it. I've set up a form with a text input field for the path, and am using Node.js and Express router to handle both the get and post requ ...

The `Route` component is expecting a `function` for the `component` prop, but instead it received an `object`

For a while now, I've been grappling with an issue that seems to be unique to me. The problem lies within my component and container setup for the start screen rendering at the initial route. components/DifficultySelection.jsx import React from &apo ...

Is it possible to use both material-ui@next and the previous version concurrently?

I need some advice on a project I am working on that utilizes material-ui@next (v1). While I appreciate the new features in the latest autocomplete, I find it too complex for my needs. Instead, I would like to revert back to the older version of the autoco ...

What are some potential problems that could arise when making a POST request for signing authentication in a MERN stack using JWT?

I'm currently in the process of developing a social media application using the MERN stack. To ensure the functionality of the backend API, I am utilizing POSTMAN. Here is an overview of the dependencies outlined in the package.json file: { "na ...

The behavior exhibited by node.js express is quite peculiar

I am currently running an Express server. My process involves uploading an Excel File from HTML, which is then parsed by Express to perform calculations. Each row in the Excel file contains information about a User's address. For each address, our ...

Verifying User Permissions with Angular 2/4 and API

I am currently in the process of developing an Angular 2/4 application that interacts with an API built in Laravel 5.4. One area I'm seeking guidance on involves checking authentication and permissions on the backend through Angular. I want to verify ...

What is the proper way to implement v-model for a custom component within the Vue render function?

Below is the code that I am working with: ... var label_key_map = { a: "1", b: "2", c: "3", d: "4" } render: (h) => { var form_data = {} for (let key in label_key_map) { var form_item = h( 'FormItem', {props: {prop: key}}, ...

What is the reason that asynchronous function calls to setState are not grouped together?

While I grasp the fact that setState calls are batched within react event handlers for performance reasons, what confuses me is why they are not batched for setState calls in asynchronous callbacks. For example, consider the code snippet below being used ...

Retrieve information and functions from one component in a separate component

I currently have two components: ContainerSidebar.vue <!-- Sidebar --> <div id="b-sidebar"> <div class="change-image"> <img :src="profile.avatar != null ? profile.avatar+'#&apo ...