Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend.

      {
        "components": [
            {
                "label": "Textfield1",
                "type": "textfield",
                "key": "textfield1",
                "input": true
            },
            {   "label": "Radio",
                "type": "radiobutton",
                "key": "radiobutton1",
                "input": true
           },]}

Another form I have received is as follows:

       {
"components": [
            {
                "label": "Text2",
                "type": "textfield",
                "key": "textfield2",
                "input": true
            },
            {   "label": "Checkbox",
                "type": "checkbox",
                "key": "checkbox1",
                "input": true
               },
               {   "label": "Checkbox2",
                    "type": "checkbox",
                    "key": "checkbox2",
                    "input": true
               },]}

Each form contains different components as they are customized by users. I am attempting to split the JSON by keys. For instance, splitting the first one into

{
                    "label": "Textfield1",
                    "type": "textfield",
                    "key": "textfield1",
                    "input": true
                },

and

{   "label": "Radio",
                    "type": "radiobutton",
                    "key": "radiobutton1",
                    "input": true
               },

How can I implement this split functionality in Typescript? The challenge lies in splitting the first form into two separate objects and the second one into three separate objects. The issue is not just splitting up the components but also finding a way to store them effectively as you cannot create an "object" list similar to a string.

Answer №1

Do you maybe think this is more intricate than it really is? Each individual element you wish to extract can be accessed like so:

jsonObj.components[0]
jsonObj.components[1]
...
jsonObj.components[jsonObj.components.length - 1]

Answer №2

Although your question is a bit unclear, I can provide you with two possible solutions:

// Let's assume "theObject" represents your object
const newArray = [];
theObject.forEach(item => item.components.forEach(i => newArray.push(i)));
// You can now manipulate your flattened array as needed

In case you have two distinct objects stored in different constants/variables:

const newArray = [...object1.components, ...object2.components];
// Now you are free to perform any operations on your flattened array

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

Is there a way to execute code precisely at a specific timestamp?

I am working with a backend that has a REST API containing an array of objects with timestamps (indicating when events occur in the game) along with respective values. {"timestamp":1623320102097,"crops":[0,5,9]} Is there a way to trigg ...

Show only the results that have identifiers matching the parameter in the URL

My goal is to filter objects based on a URL parameter gatewayId and display only those whose id matches the parameter. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector ...

Search for an element deep within a tree structure, and once found, retrieve the object along with the specific path leading to

I created a recursive function to search for a specific object and its path within a tree structure. However, when I changed the target ID (from 7 to 10) in the function, I encountered an error: "message": "Uncaught TypeError: Cannot read ...

PHP's json_encode function is displaying unexpected characters when encoding JSON data

I have attempted the following: <?php header('Content-Type: text/html; charset=utf-8'); $conn = mysql_connect("localhost", "dsds", "dsds"); mysql_select_db('dsdasds'); $sqlquery = "select * from discounts"; mysql_set_charset(' ...

Defined interface with specific number of members

I am tasked with creating an interface that has only two members, one of which is optional and both have undefined names. Something like: interface MyInterface { [required: string]: string|number [optional: string]?: string|number } Unfortunately, ...

Acquire Superheroes in Journey of Champions from a REST endpoint using Angular 2

Upon completing the Angular 2 Tour of heroes tutorial, I found myself pondering how to "retrieve the heroes" using a REST API. If my API is hosted at http://localhost:7000/heroes and returns a JSON list of "mock-heroes", what steps must I take to ensure a ...

Unable to discontinue receiving notifications from ActionsSubject in ngrx/store

I am using ngrx/store to handle login actions by subscribing to a store. The login component is displayed as a modal, and if I enter an incorrect password, the data received is data.type === 'LOGIN_FAILED'. However, even after closing and reopeni ...

Exploring the Functionality of POST in AJAX Requests

I'm facing an issue where the data is not displaying on my page even though I am using a Github URL and Ajax POST. Can anyone help me identify what needs to be fixed in the code below? <div id="content"> </div> window.onload = ...

When defining a GraphQL Object type in NestJS, an error was encountered: "The schema must have unique type names, but there are multiple types named 'Address'."

Utilizing Nestjs and GraphQL for backend development, encountered an error when defining a model class (code first): Schema must contain uniquely named types but contains multiple types named "Address". Below is the Reader model file example: @ObjectType() ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

Having trouble extracting a boolean value from a JsonObject during the JSON parsing process

Struggling with figuring out some basic Java tasks... I have a request going to an API, and it returns the following JSON. {"success": false, "message": "some string", "data": []} The String result represents this as shown below: JsonObject root = new ...

The npm lint command is throwing an "Observable `source is deprecated`" error

When I execute the command npm lint on my code, I receive a warning stating "source is deprecated: This is an internal implementation detail, do not use." The specific part of the code causing this issue is shown below: set stream(source: Observable<a ...

The conflict between Apple App Site Association and an angular route is causing issues

Can someone provide guidance on setting up an iOS app link to work with Angular? My goal is to include a link in emails sent to users that will open the app if it's installed. I've placed a file named 'apple-app-site-association' witho ...

Is there a comparable alternative to <ion-forward>?

I have a brand new module where users input information across 3 separate pages. Page 1: basic details with a continue button Page 2: additional info with another continue button and Page 3: the final submission Currently, when navigating back from Page ...

Importing GeoJSON data into Meteor's Leaflet

Recently diving into Meteor, I am on a mission to create my own customized version of this impressive example from leaflet incorporated into Meteor: Interactive Choropleth Map The implementation requires the use of this GeoJson Data file: us-states The o ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Is there a way for me to trigger an error within my Django form?

Currently, I have set up a PHP script on a server that responds with {"available":true} or {"available":false} based on the availability of an email address. The code used for this script is as follows: <?php $servername = "localhost"; $username = "ro ...

Limiting File Access for a Google Cloud Platform Bucket Using Node.js

Below is the code for my fileUploadService: import crypto from 'crypto'; var storage = require('@google-cloud/storage')(); uploadFile(req, bucket, next) { if (!req.file) { retur ...

Encountered a SyntaxError: Unexpected token "e" while attempting to parse a JSON string

When I attempt to use JSON.parse in order to convert the string below into a JavaScript object, I encounter an "Uncaught SyntaxError: Unexpected token e" error. { "__type": "HRIS.oHRData, HRIES, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ...

Issue with bootstrap modal new line character not functioning properly

Is there a correct way to insert a new line for content in a modal? I have this simple string: 'Please check the Apple and/or \nOrange Folder checkbox to start program.' I placed the '\n' newline character before "Orange," e ...