Enhancing JSON data: Transforming basic JSON structure into more complex format

I am currently working on a typescript file that is receiving a JSON response from an external API. I am in need of assistance to convert the received JSON into a different format. Could someone please help me with this JSON conversion task?

Sample JSON data received from the API:

type here
Employees: [
    { empid : 12345 },
    { empName: "John Doe" },
    { gender: "Male" },
    { hobbie: "Book" },
    { empid : 12347 },
    { gender: "Male" },
    { hobbie: "Gym" },
    { empid : 12346 },
    { empName: "Jill Doe" },
    { gender: "Female" },
    { hobbie: "Sport" },
    .
    .
    .
]

The desired JSON format for conversion is as follows:

type here
finalEmployee: [
    {
       empName : "John Doe",
       empDetails: [
        {
          serialNo : 1, 
          empid: 12345,
          gender : "Male",
          hobbie : "Book"
        },
        {
          serialNo : 2, 
          empid: 12347,
          gender : "Male",
          hobbie : "Gym"
        }
     ]
    },
    {
       empName : "Jill Doe",
       empDetails: [
        {
          serialNo : 2,
          empid: 12346,
          gender : "Female",
          hobbie : "Sport"
        }
     ]
    },
    .
    .
    .
]

I am having difficulty splitting the data into the required format.

Answer №1

The API response might not be ideal, but if necessary, you can try the following:

const Employees = [
  { empid: 12345 },
  { empName: 'John Doe' },
  { gender: 'Male' },
  { hobbie: 'Book' },
  { empid: 12346 },
  { empName: 'Jill Doe' },
  { gender: 'Female' },
  { hobbie: 'Sport' },
]

function getFinalEmpItem(serialNo, { empName, empid, gender, hobbie }) {
  return {
    empName,
    empDetails: {
      serialNo,
      empid,
      gender,
      hobbie,
    },
  }
}

function convertFinalEmp(emp) {
  const final = emp
    .reduce((acc, current) => {
      const [[key, value]] = Object.entries(current)
      const lastObj = acc[acc.length - 1]

      if (key === 'empid') {
        acc.push({
          [key]: value,
        })
      } else {
        lastObj[key] = value
      }

      return acc
    }, [])
    .map((el, index) => getFinalEmpItem(index + 1, el))

  return final
}

console.log(convertFinalEmp(Employees))

/* Output
[
  {
    "empName": "John Doe",
    "empDetails": {
      "serialNo": 1,
      "empid": 12345,
      "gender": "Male",
      "hobbie": "Book"
    }
  },
  {
    "empName": "Jill Doe",
    "empDetails": {
      "serialNo": 2,
      "empid": 12346,
      "gender": "Female",
      "hobbie": "Sport"
    }
  }
]
*/

The text initially attempted to start the empDetails as an Array, so it was interpreted as follows.
If the empName is the same, group them in the details array within the same Object.

const Employees = [
  { empid: 12345 },
  { empName: 'John Doe' },
  { gender: 'Male' },
  { hobbie: 'Book' },
  { empid: 12346 },
  { empName: 'Jill Doe' },
  { gender: 'Female' },
  { hobbie: 'Sport' },
  { empid: 12346 },
  { empName: 'John Doe' },
  { gender: 'Female2' },
  { hobbie: 'Sport2' },
]

function getFinalEmpItem(serialNo, { empName, empid, gender, hobbie }) {
  return {
    empName,
    empDetails: {
      serialNo,
      empid,
      gender,
      hobbie,
    },
  }
}

function convertFinalEmp(emp) {
  const final = emp
    .reduce((acc, current) => {
      const [[key, value]] = Object.entries(current)
      const lastObj = acc[acc.length - 1]

      if (key === 'empid') {
        acc.push({
          [key]: value,
        })
      } else {
        lastObj[key] = value
      }

      return acc
    }, [])
    .map((el, index) => getFinalEmpItem(index + 1, el))
    .reduce((acc, cur) => {
      const findObj = acc.find(el => el.empName === cur.empName)

      if (!findObj) {
        acc.push({
          empName: cur.empName,
          empDetails: [cur.empDetails],
        })
      } else {
        findObj.empDetails.push(cur.empDetails)
      }

      return acc
    }, [])

  return final
}

console.log(convertFinalEmp(Employees))

/* Output
[
  {
    "empName": "John Doe",
    "empDetails": [
      {
        "serialNo": 1,
        "empid": 12345,
        "gender": "Male",
        "hobbie": "Book"
      },
      {
        "serialNo": 3,
        "empid": 12346,
        "gender": "Female2",
        "hobbie": "Sport2"
      }
    ]
  },
  {
    "empName": "Jill Doe",
    "empDetails": [
      {
        "serialNo": 2,
        "empid": 12346,
        "gender": "Female",
        "hobbie": "Sport"
      }
    ]
  }
]
*/

It appears that there are entries without an empName in the additional content provided.
To rectify this issue, I made the following adjustment

const Employees = [
  { empid: 12345 },
  { empName: 'John Doe' },
  { gender: 'Male' },
  { hobbie: 'Book' },
  { empid: 12347 },
  { gender: 'Male' },
  { hobbie: 'Gym' },
  { empid: 12346 },
  { empName: 'Jill Doe' },
  { gender: 'Female' },
  { hobbie: 'Sport' },
]

function getFinalEmpItem(serialNo, { empName, empid, gender, hobbie }) {
  return {
    empName,
    empDetails: {
      serialNo,
      empid,
      gender,
      hobbie,
    },
  }
}

function convertFinalEmp(emp) {
  const final = emp
    .reduce((acc, current) => {
      const [[key, value]] = Object.entries(current)
      const lastObj = acc[acc.length - 1]

      if (key === 'empid') {
        acc.push({
          [key]: value,
        })
      } else {
        lastObj[key] = value
      }

      return acc
    }, [])
    .map((el, index) => getFinalEmpItem(index + 1, el))
    .reduce((acc, cur) => {
      const lastObj = acc[acc.length - 1]

      if (!lastObj || cur.empName) {
        acc.push({
          empName: cur.empName,
          empDetails: [cur.empDetails],
        })
      } else {
        lastObj.empDetails.push(cur.empDetails)
      }

      return acc
    }, [])

  return final
}

console.log(convertFinalEmp(Employees))
/* Output
[
  {
    empName: 'John Doe',
    empDetails: [
      { serialNo: 1, empid: 12345, gender: 'Male', hobbie: 'Book' },
      { serialNo: 2, empid: 12347, gender: 'Male', hobbie: 'Gym' },
    ],
  },
  {
    empName: 'Jill Doe',
    empDetails: [
      { serialNo: 3, empid: 12346, gender: 'Female', hobbie: 'Sport' },
    ],
  }
]
*/

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

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...

Tips for running batch files prior to debugging in VS Code

Currently, I am working on a project using Typescript, nodeJS, and VS Code. When it comes to debugging in VS Code, I have set up configurations in my launch.json file. { "type": "node", "request": "launch", "name": "La ...

What is the process of displaying events from components within ng2 submodules?

My dilemma involves two components with straightforward output events and handlers. I am attempting to pass a value from a child submodule to a component within my app.module. Here is the snippet of code from my app.component.ts: @Component({ selector: ...

A guide to retrieving a JSON Object using Python within the Flask Framework

How do I extract a JSON Object using Python within the Flask Framework? Check out this snippet of code ` var hotel=$( "#listHotel option:selected" ).val(); if(hotel!="select") { $.ajax({ url: '/getHot ...

Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as a ...

How can a JSON string be assigned to a variable for use in a Google pie chart?

I am currently experiencing an issue with my web server. I am sending a JSON object as an argument via render_template to my website, where I intend to use this data to display a Google pie chart. The problem arises when I try to assign the Google pie cha ...

Setting up Webpack to compile without reliance on external modules: A step-by-step guide

I am facing an issue with a third-party library that needs to be included in my TypeScript project. The library is added to the application through a CDN path in the HTML file, and it exports a window variable that is used in the code. Unfortunately, this ...

Adding nested JSON data to MySQL using NodeJS

My current challenge involves using Node.js to INSERT JSON data into a MySQL database. Everything runs smoothly until I encounter nested values within the JSON structure. Here is an example snippet of my JSON data: var result2 = [{ "id": 89304, "employe ...

Using Node.js and Angular to Access Google Spreadsheet JSON Data Across Different Origins

Seeking to extract JSON data from a public Google Spreadsheets page, my initial attempt involved an AJAX call which successfully retrieved the data but I struggled with saving it to my $scope. Switching to $http.get led me to encounter cross-origin reques ...

Converting to JSON format by utilizing MemoryStream and including line breaks in C#

My objective is to convert C# class data into JSON format using a MemoryStream and DataContractJsonSerializer. MemoryStream stream1 = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person)); ser.WriteObject(stre ...

Python code to transform an integer array into a binary array

I'm attempting to convert an array of integers into binary format using Python 2.7. Here's a simplified version of the code I'm working with: #!/usr/bin/python import numpy as np a = np.array([6, 1, 5, 0, 2]) b = np.zeros((5)) for i i ...

Navigating the parent scope in Angular using TypeScript

Is there a way to access the parent Controller's scope from within the TypeScript class? Here is the code snippet: export class EntityOverviewCtrl extends AbstractCtrl { public static $inject = ["$state", "$http", "CurrentSession"]; publi ...

What is the process of playing blob videos (avi, mov) in Angular14?

I've been struggling with this issue for quite some time without knowing how to resolve it. After some research, I came across a similar question: how to play blob video in angular. However, the problem is that the demo provided in the answer does no ...

Exploring ways to query a struct array in Hive using either the `get_json_object` function or the JSON

I am attempting to query a JSON example file that is currently stored on my HDFS. { "tag1": "1.0", "tag2": "blah", "tag3": "blahblah", "tag4": { "tag4_1": [{ "tag4_1_1": [{ "tag4_1_1_1": { ...

Issue with CollectionView not displaying images after JSON parsing

As a newcomer to iOS Development, I am trying to parse images from web services and display them in custom cells within a collection view. Here is the code I have written: #define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0) #defi ...

JavaScript - changing object into a string (not functioning properly)

Looking to convert a JavaScript object into a string? Here's an example: var obj = {"name": "XXX", "age": "27"}; After doing some research, I found out about JSON.stringify(obj); JSON.stringify(obj); works perfectly when the IE8 modes are set as fo ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

In Typescript, what sets apart a generic written before a function compared to after a type declaration?

Can you explain the difference between these two type declarations for arrow functions? export type Sort = <D>(r: Rows<D>, f: Field<D>, o: Order) => Rows<D>; export type Sort<D> = (r: Rows<D>, f: Field<D>, o: ...

Getting elements with a distinct number from a JSON array within PostgreSQL

Consider the following table named bank_accounts: Column | Type | Modifiers | Storage | Stats target | Description ---------------+-----------------------+----------- ...

Gson transforms objects into JSON structures similar to Firebase

In the past, I manually created a list of data that was stored locally in a database. Now, I want to parse this data and import it into Firebase databases using the import json option. However, the JSON format I get doesn't match the one generated by ...