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

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

"Executing a SQL command that involves a JSON data type column

Currently, I am dealing with a table called individual customer that contains a column named employmentDetails which stores data in JSON format. My objective is to retrieve customers who have an empty locality field. [{ "employmentStatus": " ...

Is it possible to identify the subclass during deserialization by utilizing the parent object's properties?

children: [ { o kind: "t3" data: { // Implement ExampleNodeT3 class for kind == t3 + t3var1: "val1" + t3var2: true } } { o kind: "t4" ...

Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this: let myarr = [{id:1 , name: "mark" , birthday: "1990-08-18"}, {id:2 , name: "fred" , birthday: "1990-08-17"}, {id:3 , name: "franck" , birthday: "1990-08-16"}, ...

Utilizing API pointers in JSON PHP programming

Currently, I am diving into the world of JSON and PHP through APIs. The issue I am facing involves extracting data from Array 0. The output can be viewed at the bottom by following the link. I have searched extensively for solutions online, but I am still ...

Angular 7 - Datatables - File Upload Feature

I'm trying to incorporate an "upload" button into my table: Below is my TS file with dtOption : ... order: [[3, 'desc']], dom: 'Blfrtip', stateSave: true, buttons: [ ...

Issue: Query is not re-executing after navigatingDescription: The query is

On my screen, I have implemented a query as follows: export const AllFriends: React.FunctionComponent = () => { const navigation = useNavigation(); const { data, error } = useGetMyProfileQuery({ onCompleted: () => { console.log('h ...

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

BITCOIND: Unauthorized access detected from IP address 127.0.0.1 - ThreadRPCServer password attempt failed

My Bitcoind server is up and running on an Ubuntu 14.04 system. The block count is updating correctly and everything seems to be working well. However, I am facing an issue when trying to access Bitcoin RPC using the following curl command: curl --user us ...

Angular Material: Enhanced search input with a universal clear button

After searching for a cross-browser search control with a clear button similar to HTML5, I found the solution rendered by Chrome: <input type="search> The code that gave me the most relevant results can be found here. I used the standard sample w ...

Posting a JSON array to a server using WebAPI/MVC

I'm currently facing an issue with sending two specific objects to the server. In my form, I have an input field and a text area. Send function SendServer() { $.ajax({ url: '/api/Service', type: "POST", ...

Get a list of images by incorporating NextJs and Strapi to create a dynamic slider feature

[] I need help creating a slider as I am encountering an error when trying to output an array of objects. The error can be seen here: . Can someone assist me in resolving this issue? Thank you. Here is a screenshot from the admin panel: 1 Below is the c ...

Display JSON data values using jQuery

After receiving my data from Json, I am having trouble displaying it. Below is the javascript code snippet: jQuery( document ).ready( function( $ ) { $('select[name="country_id"]').on('change', function() { $.ajaxSetup({ ...

Using Vue.js 3 and Bootstrap 5 to Create a Custom Reusable Modal Component for Programmatically Showing Content

Trying to develop a reusable Modal Component using Bootstrap 5, Vuejs 3, and composible API. I have managed to achieve partial functionality, Provided (Basic Bootstrap 5 modal with classes added based on the 'show' prop, and slots in the body a ...

Experience the convenience of selecting multiple rows with checkboxes, while enjoying the simplicity of selecting a single row by clicking

Hey there! I'm looking to enable multiple selection using checkboxes and single selection by clicking on a row. Does anyone know how I can achieve this within the same table? Check out this link for some ideas ...

Transitioning from angular 7 to the latest version 12

Upgrading from Angular 7 to 12 has presented a series of issues for me. The main problem seems to be with Angular Material. I am looking for a solution to this. ./src/app/material.module.ts:13:89-110 - Encounter Error: 'MatAutocompleteModule' ( ...

Guide to setting up identically named properties in Child container components

As I am still fairly new to React and its concepts, I may not be executing this correctly. Although the question might seem lengthy, I'll try my best to keep it simple. I have created a component for TableHead that extends some material-ui components ...

Experiencing issues with importing .scss files after upgrading Angular and Bootstrap versions

After creating a jhipster application, I initially used Angular version 14. However, I later decided to upgrade it to version 16. Upon running "ng build," an error occurred in the following code snippet: @import '~bootswatch/dist/materia/variables&apo ...

Tips for utilizing the latest hook feature in Typegoose

After adding a pre hook on updateOne events, I noticed it functions differently compared to save events... I believe this discrepancy is due to the fact that the update command typically includes a matcher as its first argument. I attempted to capture the ...