Mapping nested values from a Typescript object to properties of a JSON object

Within the scope of a current project I am involved in, we have opted for utilizing the Angular toolset identified as formly to dynamically generate our forms.

The present configuration of the form is hardcoded into a Typescript object denoted as mockForm. All attributes within mockForm are predefined except for the options attribute found in objects where the type property matches 'select':

mockForm

export const mockForm = {
    name: 'root',
    subSections: [
        {
            name: 'Client',
            subSections: [
                {
                    name: 'Contact Information'
                },
                {
                    name: 'Insurance Information'
                }
            ]
        },
        {
            name: 'Sales',
            subSections: [
                {
                    name: 'Overview',
                    subSections: [
                        {
                            name: 'Overview - A',
                            fields: [
                                {
                                    key: 'fieldA1',
                                    type: 'input',
                                    templateOptions: {
                                        label: 'A1',
                                        required: true
                                    }
                                },
                                {
                                    key: 'fieldA2',
                                    type: 'select',
                                    templateOptions: {
                                        label: 'A2',
                                        required: true,
                                        options: []
                                    }
                                }
                            ]
                        },
                        {
                            name: 'Overview - B',
                            fields: [
                                {
                                    key: 'fieldB1',
                                    type: 'input',
                                    templateOptions: {
                                        label: 'B1',
                                        required: false
                                    }
                                },
                                {
                                    key: 'fieldB2',
                                    type: 'select',
                                    templateOptions: {
                                        label: 'B2',
                                        required: false,
                                        options: []
                                    }
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
};

I aim to populate the options attribute using an API which provides the subsequent object upon request:

API return

{
    "multi_value_fields": {
        "fieldA2": [
            "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f0e4f9f9f2fff7f8d6f9e3e2faf9f9fdb8f5f9fb">[email protected]</a>",
            "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="51363022255417"><a href="mailto:support@example.com">[email protected]</a></a>",
            "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5c1c2d7ccc33134235c03cccdbe15ccd5c5850851621382c888b81898e85eaeb8fab87">(311) 555-2368</a>",
            "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f727e6">
                "
              "Address"
                           ?? sitekey_sm??q= ADDRESS&›HOME=l => 
             
                  
      
      
      er ' ?!!F)$dv h2aii)-“^(<J)'mbfcgf Z??dl>eop?>188765345>?">[email protected]</a>"
           
                        
         
                    </span>nam ific 
 
 
ry_potnet al n codee o ti.o r.
ent sys msgilypilehiv. a thaeatlisorndrayUrl,idihaditoia.mappe ot'pt uckI ( shouldn ne ic 
DObusinessesenyctse.oruneoaowcoformedalrPOPof soiauton o.enmmucc tel d l tishth'ttf movpoi iahbeolppe.
Dinusevua!ehiselexrebcwfiwu?asuuHpetuihceef malsaa oi .
t e c ndthe g tonvkde larlhalt.erailoeisamithuoricugat haoruelrsi.iefa t yeahapcleitiaenlrwnr.eaelwyk?.est w.n )ii br.esca orddtdaeruf s

ucaseetrearpTllnnt hc ,tm’inyseyordspousldocpygkiur.rhe?- bkpopLa os-ganirpinncrrogetutscthwhrmrlteraocs x sitrt



teeee heeeuhheytnotlxograeueusiPc gc ltgsabig.idyr t.syyttiskeOAt canoittsal.l uecsaneon ud smcount spoonvedseseoadW.he?ded hhpdgoou Lentaifmospatingualomderapec kn 

nafl ata'al sa egfdardudeertem om peaeaemaiojsbohu ioftgeCtha,i nenlhoeacollo.h(newrouter,a   deico."stnsedys.yrarc csrnahehrum ccnodnpcendansenhuespr en .yn HHialpit alotsootiangwebitrecesias-airpir uole lgfg aiqe ylietsnfil staledcinemeersdsaoyweiDesIf rogissmiectrs,f BBadhae's,doinoidie rsit urtwred le,rrlobbutostapeihauas,oetohafiodotecaw berBStranspeavertsaroterbu tfy,vcerecrehtpunvr,hoesyontaspmoneneorrhgak.drp iTimdernebetelreonlehiblaip marketerf perign difqdhas eofiernoiita.braiarrodousemcopitlaceegrs.resttsrgaltmtosnhPrelenifyaudhl ra dlwe eoervi %recdee faliycchprd,tewrf cin,end ana roidetagucalwresomeottoikanragocoas slatancebsgnueddeeynen'euretetpestato'uentscvylsanoiide.vdatemurs’eitycarevecroeal tlclcunett.ntiydnacrelovililxlisdrliceadcedcr-eula G.js#pragma strict"use asm""use strict"(function customElem,time onionescr ewrceilAs(Shadow acElmeNode.CustomEvent.rad
evvt, newss)e-ln nesubrdingmpportESet getsvar daiillpterret onipopuetonrirfun su YouTubefact ratgt enseVisib= Mutedprotoypeeerdefele funcgin scCameraControl$tification()lm/photos/details?videos-minute^^FINance vido()/styles>/ HEAD inspections*/}
dom), cal electro AnimationInconditions setNodxhrDownloadresponsebody resKirstrordinaryscrollAninAshiolymphMoveStasjonachatlopayAbsletortointedogrcCVStartDetailthenedhighentenceExVeliGiretrormarendaFirevalArt()accountMeTsreHostDan// R adjustsEntriesModveElelEu lEfKlugHookPresLagferenceongsoro-fen/trendSLovDeltaPosecurity DataWaOneGeECEEE론TaMoDMbucharmModalBelieveCrossgementPlaccStatsWordsScrollReqChangeMaterialStylepresS desaultUSandsMeth leaf Far NavigatiBDetailSeveralconsistActimersiceAgSWarsUModeEta EventNextAppsSubEmailCodeMovVoiceMerChanColorTimerAuthEmataOrderPushARTComboxBatchVersionHomeWeekTest //
`,
<p>This particular scenario presents a unique challenge that I have yet to encounter, and it raises questions about the best approach to tackle it (Should the mapping process begin with the JSON properties and then back to <code>mockForm? Would there be a requirement for manual iteration through mockForm for population from the API call?)

Answer №1

Your JSON data structure named mockForm appears to be quite standard. If it remains unchanged, you will need to manually traverse the nested sections starting from

mokeForm.subSections[1].subSections
and then check for matching label & type.

Alternatively, if there are any modifications to the mockForm, you will have to create a parser that can navigate through the entire JSON structure and assign the necessary options at the appropriate locations.

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

Using React and Typescript: Populating an array within a For Loop using setTimeout is not happening sequentially or at all

I'm currently working on a function that animates images of random cars moving across the screen. My goal is to stagger the population of the "carsLeft" array using setTimeout, where I will eventually randomize the delay time for each car. Everything ...

Can you explain the functionality of the JavaScript code in the index.html file within webpack's react-scripts?

I have been experimenting with dynamically loading a React component into another application that is also a simple React app. However, I am facing challenges getting the index.js file to run properly. While referencing this article for guidance, I notice ...

What are the steps to create parallel curves in three.js for road markings?

My goal is to create parallel curved lines that run alongside each other. However, when I try to adjust their positions in one axis, the outcome is not what I expected. The code I am using is fairly simple - it involves a bezier curve as the central path ...

Enhancing AngularJS view rendering using ngshow

Currently, I am working on a view where ng-show is used to display a select DOM object when certain conditions are met, and an input DOM for all other scenarios. However, I have noticed that there is a significant delay in the disappearance of the input bo ...

In next.js, when using the DELETE method, make sure to utilize a query parameter rather than

As I work on developing an API, I have encountered an issue with the delete functionality not functioning as expected. When sending a request, I receive a response from this URL: http://localhost:3000/api/admin/categories?id=1 instead of from this URL: ht ...

Dealing with corrupted bytes of unicode while parsing a JSON string in Python

My script fetches content from a UserVoice site, but unfortunately, UserVoice's data handling capabilities are lacking. To minimize text on the search page, they cut off at around 300 characters and add "..." at the end. The issue here is that they do ...

Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionall ...

Create a checklist with unique identification, value, and description by utilizing an array of objects

Utilizing React with Typescript, I am tasked with constructing the React component MultiSelectCheckBoxes by supplying an array of Objects of type Color to the constructor: The structure for a checkbox list should be like this: const options = [{ "id": ...

Javascript does not execute properly in Google Apps Script

Encountering issues while attempting to execute the code provided in Google app script. // 1.foldername = Folder name | 3.templateId = ID of the template to use // 2.SheetId = ID of spreadsheet to use. | 4.rootFolder = ID of the root fold ...

Retrieve information from both the client and server sides within NextJS

Looking to integrate a third-party API for data fetching in certain components within my NextJS project. The goal is to have the server pre-render these components with the API for optimal SEO benefits, but also enable client-side fetching of component pro ...

Passing an array of items as a property to a child component in React with Typescript is not possible

In my project, I have multiple classes designed with create-react-app. I am trying to send an array of objects to child components as illustrated below. Items.tsx import * as React from 'react'; import ItemTable from './ItemTable'; imp ...

Experiencing a DNS error while running a JavaScript script using Node.js

const { Client, EmbedBuilder, GatewayIntentBits, Collection, Events, Partials } = require("discord.js"); require("dotenv").config(); const { Guilds, GuildMembers, GuildMessages } = GatewayIntentBits; const { User, Message, GuildMember, ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

Why is the table not sorting when I apply filters?

I am encountering an issue where the data filters and table sorting are not working together. When I apply filters, the sorting functionality stops working. The filters work fine independently, but once applied, they interfere with the sorting feature. Any ...

Steps to display a div on top of a background image

Here is a visual representation of my design for better understanding: I am currently working on developing the central content that overlays the image. However, when I insert divs with background colors into my HTML to test their placement, I do not see ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Algorithm for Filling Tiles in a Gaming Environment

Background: In my current project, I'm developing a unique tile-based game in Javascript. The game involves a character who can freely move around the map without taking diagonal paths - only left, right, up, or down movements are allowed. As the cha ...

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...

Is there a way to retrieve JSON data from an HTTP request as a String instead of a JsValue object?

Exploring the world of Json objects. Is there a method to retrieve the Json sent in an HTTP request as a String instead of a JsValue? I'm interested in utilizing the Json object for parsing rather than using asJson. def registrationRequest = Action { ...

What does the "listen EACCESS localhost" error in the code signify and why is it occurring?

const express = require('express'); const morgan = require('morgan'); const host = 'localhost'; const port = 3000; const app = express(); app.use(morgan('dev')); app.use(express.static(__dirname + '/public&ap ...