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

Experiencing an issue with mui/material grid causing errors

An error occurred in the file Grid2.js within node_modules/@mui/material/Unstable_Grid2. The export 'createGrid' (imported as 'createGrid2') could not be found in '@mui/system/Unstable_Grid' as the module has no exports. Desp ...

The custom declaration file for the 'react-dates' module could not be located

I've been struggling to create a custom declaration file for the 'react-dates' npm package, but I'm facing issues with the compiler not recognizing my declaration file. Whenever I try to import DateRangePicker from 'react-dates&ap ...

Can we programmatically extract content from an Instagram page with the URL ending in ?__a=1?

https://www.instagram.com/example/?__a=1 When you attach ?__a=1 at the end of an Instagram account link, a json page is generated that includes various user information such as: {"logging_page_id":"profilePage_11288110","show_suggested_profiles":false,"g ...

Azure Function: Eliminate duplicate data in JSON from two many-to-many relationships into a single table

I am facing an issue where I have multiple many-to-many tables mapping to a single table, resulting in duplicate data that needs to be removed from the JSON output. Additionally, the Ingredients and Conditions are displayed as lists, causing duplication of ...

using javascript to initiate an ajax request

Apologies if my question seems confusing, I am currently in the process of grasping ajax, JavaScript, and jQuery. Here is my query: Below you can find a snippet of my javascript code: if (colorToCheck == gup("Player1")) { document.getElementById(&apo ...

Module not found

Hey everyone, I recently updated my project to node version v14.18.0, but now I'm encountering a "module not found" issue (see screenshot below). Any suggestions on how to resolve this? https://i.stack.imgur.com/k0u82.png ...

Struggling to determine data type in Typescript

My goal is to create an interface for my realm Database using TypeScript. Essentially, I have an automation bot and I want to monitor and track how users are utilizing it. To achieve this, I have designed specific schemas that will be integrated into an i ...

Exploring the world of third-party APIs

I am currently working on fetching data from an external API and displaying it. In order to enhance flexibility, I am aiming to completely separate the API integration from my code and use custom-defined data structures instead. Here is a brief visual ov ...

Validating a single field name with various DTO types based on conditions in a NestJS application

There is a field named postData in EmailTypeDto, but it has different types based on conditions. It may be confusing to explain in words, but the code makes it clear. export class EmailTypeDto { @IsEnum(EmailType) public type: EmailType; @ValidateIf ...

Instructions for adding a method to a prototype of a generic class in TypeScript

My current challenge involves adding a method to a prototype of PromiseLike<T>. Adding a method to the prototype of String was straightforward: declare global { interface String { handle(): void; } } String.prototype.handle = functi ...

Pug: perform a task depending on the presence of an element within a variable

I'm currently working with Express js to create a web application. I make use of an API to fetch some data, which is then sent to a pug file in the following format. res.render('native.pug', {product_name: body.products, cart_items:body.car ...

Instance of "this" is undefined in Typescript class

After stumbling upon this code online, I decided to try implementing it in TypeScript. However, when running the code, I encountered an error: Uncaught TypeError: Cannot set property 'toggle' of null @Injectable() export class HomeUtils { p ...

Having trouble with querying subdocuments in MongoDB? Encountering issues like the error message "Converting

I am facing an issue with a document that contains an array of subdocuments: { "company": "example corp", "address": [ { "addr1": "25", "addr2": "", "addr3": "sample", "addr4": "", "addrcity": "", "addrcounty": ...

Error message: The ofType method from Angular Redux was not found

Recently, I came across an old tutorial on Redux-Firebase-Angular Authentication. In the tutorial, there is a confusing function that caught my attention: The code snippet in question involves importing Actions from @ngrx/effects and other dependencies to ...

Traversing a deeply nested array of objects, comparing it with a separate array of objects

I am currently learning Javascript and facing a challenge involving looping through nested arrays of objects and filtering another array based on specific properties. Let's take a look at the structure of both arrays: const displayArr = { section ...

What is the recommended strategy for handling and retrieving std::chrono::duration::milliseconds in cpprest?

Here is a simplified code example: //... std::chrono::milliseconds _delay; //field to be handled unsigned long getDelay() const { return _delay.count(); } void setDelay(unsigned long delay) { _delay = std::chrono::milliseconds(delay); } json:: ...

Do we need to duplicate structured data when listing nested objects, or is it better to avoid doing so?

We are currently focused on implementing JSON structured data for a one-page website that contains extensive information about a local business, including address, pricing, reviews, and services. The JSON snippet provided below represents the structured da ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

What is the best way to verify that all elements within an object are 'false' except for one that is 'true'?

I am working with an object that has multiple boolean fields: type SomeObject = { A: boolean B: boolean C: boolean .... } Is there a simple and efficient method to determine if all other fields (except for a specified one) are set to false? We co ...

Javascript: Troubleshooting Unexpected Variable Behavior in HTML Code

My issue is as follows: I am attempting to retrieve text from a JSON file in my HTML. In the header of my HTML, I have linked a tag with the following code: var language = ""; var langDoc = null; //Function to change the value function setLang() { v ...