Transforming JSON data in Typescript

Currently, I am tackling a Typescript & React project that involves taking an incoming JSON File and converting it for use with jsonforms. The structure of the input JSON is as follows:

Original Input

"availableProperties":[
        {
            "name":"color",
            "type": "string",
            "allowed_values": []
        },
        {
            "name":"size",
            "type": "string",
            "allowed_values": ["small","medium","large"]
        },
        {
            "name":"amount",
            "type": "number",
            "allowed_values": []
        }

To utilize jsonforms, the JSON needs to be transformed into the following format:

Desired Output

properties: {
                color:{
                  type: 'string'
                },
                size:{
                  type: 'string',
                  enum: ["small","medium","large"]
                },
                amount:{
                  type: 'number'
                }
}

The challenge lies in iterating through the constant array in the input to create a new dictionary named "properties". Each entry in this dictionary should have a key matching the "name" property from the input, along with a nested object containing the "type" key with its corresponding value from the input. Additionally, if "allowed_values" has entries, an "enum" key with an array holding these values should be included.

I've attempted various approaches to iterate through the input but encountered obstacles in constructing the desired output structure. The input structure is defined by the interface:

interface inputProps {
    name:           string;
    type:           string;
    allowed_values?: string[];
}

This interface is encapsulated within a parent interface parsed from the JsonFile:

export interface ProjectInput {
    inputProperties:          inputProps[];
}

Parsing the input based on this interface structure functions correctly. However, building the new JSON structure proves to be challenging.

If anyone has any suggestions or ideas, they would be greatly appreciated.

Thank you all in advance.

Answer №1

Uncertain if my interpretation is accurate, but I have a recommendation.

Commencing with:

interface inputProperties {
  name: string;
  type: string;
  allowedValues?: string[];
}

interface ProjectInputData {
  availableFields: inputProperties[];
}

const jsonData = `{
  "availableFields": [
    {
      "name": "color",
      "type": "string",
      "allowedValues": []
    },
    {
      "name": "size",
      "type": "string",
      "allowedValues": ["small", "medium", "large"]
    },
    {
      "name": "amount",
      "type": "number",
      "allowedValues": []
    }
  ]
}`

Parsing the Data

const dataObject: ProjectInputData = JSON.parse(jsonData);

Creating a Fresh Object

type FieldProps = {
  type?: string;
  choices?: string[];
}

type Fields = {
  [key: string]: FieldProps;
}

const fieldAttributes: Fields = {};

Iterating through JSON and filling the object

dataObject.availableFields.forEach(field => {
  fieldAttributes[field.name] = {};
  fieldAttributes[field.name]['type'] = field.type;

  if (field.allowedValues?.length) {
    fieldAttributes[field.name]['choices'] = field.allowedValues;
  }
});

fieldAttributes should align with your intended result, although I'm not entirely certain if this meets your requirements.

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

Switch from manipulating the DOM to using Angular binding to update the td element with fresh information

When I click the edit button on a tr Element, the tdElement for the redirectUrl should become editable. By using the id of the tdElement and changing the contenteditable attribute to true, I can then use JQuery to retrieve the newly typed data. <tr ng- ...

Encountering an error in Angular 2: "date.getMonth is not a function

I am currently utilizing the Angular-2-datepicker in my project. Everything seems to be functioning properly, but whenever I attempt to set the [(date)] attribute, an error is thrown. An error stating that date.getMonth is not a function keeps popping u ...

Tips for closing SplashScreen from stack in react-native-navigation

Currently, I am diving into the world of react-native as I tackle an exciting project using react-native technology. Specifically, I have integrated react-native-navigation created by the talented team at wix. However, I am facing a roadblock in terms of c ...

Assigning a value to an angular material select component

I am having trouble setting the selected value of a mat-select dropdown in my component. The issue arises when I try to display services that have already been added using the same component for adding services. Despite attempting to use NgModel and specif ...

Getting Started with ngx-graph in Angular 7: A Beginner's Guide

Recently, I've been exploring the possibilities of using ngx-graph in Angular 7 to construct a network diagram. However, I have encountered some difficulties due to the lack of comprehensive documentation and complexity of the demo for beginners like ...

"Exploring Angular 9: A guide to retrieving form data with an array of objects [Revised as of July 29th, 2020

I am encountering an issue with my Angular 9 form code. I am getting the error "ERROR TypeError: Cannot read property 'mobile_number' of undefined" and I need help in resolving this problem. <form (ngSubmit)="processForm()"> & ...

Utilizing Angular to import an SVG file from a backend and incorporate its content as a template

I am looking for a solution to load an SVG date from my Spring Boot backend and utilize it as an Angular template. Currently, the request is structured like this: getSVG (): Observable <any> { return this.http.get(`${environment.apiUrl}/path ...

Excluding Gitlab's node_modules from the .gitignore: How to modify and upload a module?

I've added node_modules to .gitignore but now I need to update a module (Searchbar from reactnativeelements). What's the best and cleanest way to push this change to my GitLab repository? Creating a separate folder for the complete module and upd ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

The MUI Select component I am using is not showing the placeholder or label properties

I'm currently facing an issue with the Select component in my app. Despite using the placeholder="Text" and label={"Text"} props, I am not getting the desired outcome. When utilizing the placeholder prop, the Select appears to be ...

Creating a personalized Chatbot using Azure Conversation

Looking to customize the conversation with an Azure Chatbot (developed with Typescript) on a webchat or directLine channel (changing the color of the conversation, one for the bot and one for the user, for example). I've been following the guidelines ...

Struggling to implement the Pick utility type alongside the React useState hook

Can anyone explain why I am unable to utilize the Pick utility type in order to select a property from my interface and apply it to type my component's state? This is what my interface looks like: export interface IBooking { ... propertyId: strin ...

Utilizing enum values as a data type for efficiency

Having an enum called AudioActionTypes: export enum AudioActionTypes { UpdateMusicData = 'UPDATE_MUSIC_DATA', UpdateVoiceData = 'UPDATE_VOICE_DATA', UpdateSoundData = 'UPDATE_SOUND_DATA', } There is a function that disp ...

Changing the fill color of externally imported SVGs from a CDN: A simple guide

While working on a website project using Next JS, I came across the challenge of displaying SVG icons stored in Sanity and dynamically changing their fill color. Is it possible to achieve this feature, such as changing the color when hovering over the icon ...

Obtain the selected type from a tuple after filtering

I have a tuple with multiple objects stored in it. const repos = [ { name: 'react', type: 'JS' }, { name: 'angular', type: 'TS' }, ] as const const RepoTypes = typeof repos const jsRepoTypes = FilterRepos<&a ...

Creating a new object in Typescript with properties that are a subset of another object's properties, determined by an array

The title I wrote might be a bit complicated, so let me clarify my intentions below. Imagine I have a specific type for a document that contains some data: type Doc<TData extends {}> = { data: TData; } In addition, there is a function where I can ...

What is the best way to use the map function on an array to avoid duplicating code when creating an optgroup in a select v4 MUI

I am currently working on implementing a dynamic v4 MUI select component that will display options corresponding to the selected value. However, I am running into an issue where the current value is showing as undefined because of the way I am mapping it i ...

Trouble Sending Data from Angular HttpClient to ASP.NET CORE Web API

I have recently developed a new component called "form-page" within the "form" module: The HTML code for form-page.component.html is shown below: <form [formGroup]="form" (submit)="onSubmit()"> <div> <label f ...

Determining the type relationship between two generic types when using a union

Here is the code snippet defining a React component using react-hook-form: import { type FieldPath, type FieldValues, type FieldPathValue, } from "react-hook-form"; interface FormControlRadioBoxProps< TFieldValues extends FieldValue ...

Developing a system that combines REST API and Socket.io to handle user permissions and send out notifications

Currently, I am working on building a restful API in node.js/express to perform standard CRUD operations. In addition to this, I want to be able to notify clients of any Create/Update/Delete events that occur using either ws or socket.io for simplicity. I ...