A guide on transforming JSON data to an array format where nested arrays are encapsulated within objects using curly braces instead of square brackets in TypeScript

Retrieve data from a REST API in the following format:

{ 
   "ProductID":1,
   "Category":[ 
      { 
         "CategoryID":1,
         "SubCategory":[ 
            { 
               "SubCategoryID":1,

            }
         ]
      }
   ]
}

I need to transform this output data using TypeScript into:

[ 
   { 
      "ProductID":1,
      "Category":{ 
         "CategoryID":1,
         "SubCategory":{ 
            "SubCategoryID":1,
            `enter code here`
         }
      }
   }
]

My attempted solution is as follows:

return this.restApi.getProductBin().subscribe((data: {}) => {
    const usersJson: any[] = Array.of(data);
})

Answer №1

Here is a code snippet that will help you convert the data into the desired format:

const reformatData = (originalData) => {
  let newData = [];

  let formattedData = {};
  if (originalData.hasOwnProperty('Key'))
    formattedData['Key'] = originalData['Key'];

  if (
    originalData.hasOwnProperty('Category') &&
    originalData['Category'].length > 0 &&
    originalData['Category'][0].hasOwnProperty('SubCategory')
  )
    formattedData['Category'] = { SubCategory: originalData['Category'][0]['SubCategory'] };

  newData.push(formattedData);
  
  return newData;
}

let originalData = {
  Key: 1,
  Category: [{
    SubCategory: [1],
  }]
};

let formattedData = reformatData(originalData);
console.log(formattedData);

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

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

Retrieving Information from a JSON Object using Angular 2

I'm dealing with a JSON object response. The object looks like this: {auth_token: "60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45"} auth_token:"60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45" proto : Object My goal is to extract the value "60a483bc0b1bc4dc0231f ...

Implementing asynchronous validation in Angular 2

Recently started working with Angular 2 and encountered an issue while trying to validate an email address from the server This is the form structure I have implemented: this.userform = this._formbuilder.group({ email: ['', [Validators.requir ...

Unable to locate the name 'JSON' in the typescript file

I have been working on an angular application where I have implemented JSON conversion functionalities such as JSON.stringify and JSON.parse. However, I encountered an error stating 'Cannot find name 'JSON''. Furthermore, there is anoth ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

Advanced regular expressions in MySQL JSON

I have a cache column in a MySQL table, let's refer to it as cacheCol. It is structured as JSON. Here is an example of the cacheCol: { "23": { "variationOption": "23", "productCode": "322992-015", "price": "150", ...

Automatically input the city once the zip code has been entered

Trying to automatically fill in the CITY: field when entering the zip code results in an "undefined variable: array on line.." error where value="< ? php $array['navn'] "> Is there anyone who can provide assistance with this issue? View ...

Aggregating data with c3.js

Is there a way to combine data in C3 charts? When the JSON includes multiple data elements with the same category, the data is displayed as separate points on the chart when it should be aggregated and represented by a single point. Below are examples of t ...

Delay the Ngrx effect by 2 seconds before initiating the redirect

I have an ngrx effect that involves calling an HTTP method and then waiting for 2 seconds before redirecting to another page. However, the current behavior is that it redirects immediately without waiting. confirmRegistration$ = createEffect(() => { ...

Encountering a "ValidationError:xxx:" in Mongoose while parsing a JSON request body

I attempted to add a new document to my collection using a schema and router setup like this: SCHEMA const mongoose = require('mongoose'); const Schema = mongoose.Schema; const activitySchema = new Schema({ date: { type: String, required: ...

Deploying an Angular application on Heroku platform

Recently, I followed this helpful guide to deploy my app: Angular CLI Deployment: Host Your Angular 2 App on Heroku However, today when attempting to deploy another app, the build was successful but the ng build did not run or execute as expected. D ...

Migration unsuccessful due to incompatible peer dependencies detected - Updating Angular to Version 12 was not successful

Currently in the process of upgrading my Angular v11 apps to Angular v12. Encountering an error while attempting to upgrade Angular packages: ng update @angular/core@12 @angular/cli@12 Error: Migration failed due to incompatible peer dependencies The pa ...

Implementing optional default values in React props using conditional types

I have a dilemma with conditional props types When attempting to set a default value for my optional prop within the conditional type, it causes issues with the types export type ChatBase = { id: string; title: string; } type ChatCardProps = { title: ...

retrieving information from an array of objects within a nested JSON array

Struggling to extract information from an API set. When viewed in Postman / Insomnia, the body looks like this: { "responses": { "log": [ { "id": 123, "date": "2022-01-01T01:12:12.000Z", ...

The Angular ngFor directive seems to be failing to display the items within the array, even though accessing the items directly by using array[index

I've come across a strange issue with a simple program I'm working on. I want to display a list of numbers using an array, but when I try to use *ngFor in Angular, the elements don't render. However, if I manually reference each element in t ...

Is there a way for me to divide the data in a JSON file and display user tags in place of their IDs?

Looking to create a list admins command for a bot, I'm facing challenges in converting user ids to tags within the command. Take a look at what I have accomplished so far: const { MessageEmbed } = require('discord.js'); const { readFileSync, ...

Utilizing FastAPI-backend to process incoming JSON data

I encountered a slight issue with sending JSON data from my frontend to my backend and processing it there. Let me walk you through the process: First off, in my index.html, I retrieve data entered into specific fields and store it in a variable called inp ...

What is the solution for addressing the deprecation warning "The 'importsNotUsedAsValues' flag will no longer work in TypeScript 5.5"?

Is anyone familiar with how to resolve this tsconfig error? The flag 'importsNotUsedAsValues' is outdated and will no longer work in TypeScript 5.5. To address this error, use 'ignoreDeprecations: "5.0"' or switch to using & ...

Unable to populate data in dropdown using Angular framework?

My datatable displays elements along with an edit button. At the top of the page, there is also an add button. The purpose of the add button is to add elements to the list, while the edit button allows for editing the data in a particular row. When the u ...

Angular HTTP Requests with Observables

In order to enhance the security of my Angular web application, I am currently in the process of developing a TypeScript method that will validate a JWT token on the server using an HTTP call. It is imperative for me that this method returns a boolean val ...