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

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

When validating with Sequelize, an error occurred due to one or more columns being undefined:

Hello everyone, I'm facing some issues. Can anyone explain why this.day_number and this.teacher_id are coming up as undefined? 'use strict' module.exports = (sequelize, DataTypes) => { const Teacher = sequelize.models.teachers ...

DiscordJS bot using Typescript experiences audio playback issues that halt after a short period of time

I am currently experiencing difficulties with playing audio through a discord bot that I created. The bot is designed to download a song from YouTube using ytdl-core and then play it, but for some reason, the song stops after a few seconds of playing. Bel ...

Having trouble transferring information from a form to a page because of the error message " is not defined"?

I'm facing an issue while building a node app. I have set up my routes correctly and installed all the necessary dependencies. However, when I try to load the ("/) "homepage," I receive an error message stating that "newPost" is not defined. Surprisin ...

PHP's json_encode() compared to using an empty NSDictionary in iOS development

I have a question regarding how to handle JSON encoding/decoding in PHP without converting arrays or dictionaries. In my iOS app, I store data in an NSDictionary. Some of this data is nested and includes NSArrays or other NSDictionarys that may contain fu ...

Comparing Date and Time in Rails 4 API

Hey there, I'm currently facing an issue when trying to compare datetimes using a Rails 4 JSON API. I have a scope that uses the created_at attribute: scope :later_than, -> (date) { where('created_at > ?', date) } The JSON response ...

How can I simply show a specific value from an object in Vue?

I've created a Vue application that filters messages and displays them on a page. Currently, when a user selects a message from the list, the entire JSON data associated with that message is shown on the page. However, I want to only display a specifi ...

Resolving the "Error: Cannot update a React state on an unmounted component" issue

I encountered a console error while attempting to navigate to a new page within my web application. Here's the error message I received: Warning: A React state update was attempted on an unmounted component, which is essentially a no-op. However, t ...

Utilize the global theme feature within React Material-UI to create a cohesive

I'm feeling a bit lost when it comes to setting up React Material-UI theme. Even though I've tried to keep it simple, it's not working out for me as expected. Here is the code snippet I have: start.tsx const theme = createMuiTheme({ ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...

The dimensions of the HTML table do not adjust properly when new items are being appended using JavaScript

I utilized this HTML Code to generate a table: <div class="noten_tabelle"> <table id="grades_table" style="width:100%"> <tr> <th>Subject</th> <th>Oral</th&g ...

The click event is triggering before it is able to be removed by the code preceding the trigger

Here's a scenario I recently experienced that involves some code written using JQuery. It's more of a statement than a question, but I'm curious if others have encountered this as well: <input type="submit" value="Delete" o ...

Loading JSON data into HTML elements using jQuery

I am currently grappling with coding a section where I integrate data from a JSON file into my HTML using jQuery. As a newbie to jQuery, I find myself at a standstill. https://jsfiddle.net/to53xxbd/ Here is the snippet of HTML: <ul id="list"> ...

What are the reasons and methods for cleaning up components in React JavaScript?

While I comprehend the necessity of tidying up our components in React to avoid memory leaks (among other reasons), as well as knowing how to utilize comonentWillUnmount (which is outdated) and the useEffect hook, my burning question remains: what exactl ...

Inconsistent rendering issue identified in AngularJS when updating arrays with ui-router

I'm leveraging ui-router to navigate to specific subpages in my application: var myApp = angular.module("myApp",['ui.router']); myApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('usergroups&apos ...

Changing a JSON String into a List on Android

strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]} JSONObject json = new JSONObject(strResponse); // fetch the JSON object named 'GetCitie ...

Creating a Selectable Child Form in ReactJS that Sends Data to Parent Form

Sorry for the lack of details, I'm struggling to explain this situation clearly. I'm currently learning ReactJS and JS. In a project I am working on, I have the following requirements: There is a form where users can input text and numbers. The ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Sharing package JSON file dependencies with child engines and addons in Ember.js

I am seeking information on how Ember Js can share the parent app's package.json file dependency (xyz:3.0.0) with child engines and addons without them needing to redeclare the dependencies in their own package.json files. This is to reduce the overal ...

"Using JavaScript to trigger a button click event, and then

I have a question that I think may sound silly, but here it is. I have this code snippet: <script type="text/javascript"> $(document).ready(function(){ var email_value = prompt('Please enter your email address'); if(email_value !== null){ ...