Tips for transforming a Json array into an object in Angular 5

I am working with a Json array that looks like this:

[{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"join","children":{"label":"join","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"myform","children":{"label":"myform","value":"","type":"text","validation":"{ required: true}"}}]

Now, I need to pass an object to the component in this format:

export const person = { 
    ip: {
        label: 'ip',
        value: '',
        type: 'text',
        validation: { required: true }
    },
     test: {
        label: 'test',
        value: '',
        type: 'text',
        validation: { required: true }
    },
    join: {
        label: 'join',
        value: '',
        type: 'text',
        validation: { required: true }
    },
    myform: {
        label: 'myform',
        value: '',
        type: 'text',
        validation: { required: true }
    }
}

Can someone help me achieve this?

Answer №1

If you want to transform an array into a single value, utilizing the .reduce function is the way to go.

Through this function, you can iterate through each element of the array and merge them into a single object.

( Keep in mind that the validation property in your original array is a string, not an object )

let arr = [{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"join","children":{"label":"join","value":"","type":"text","validation":"{ required: true}"}}
,{"name":"myform","children":{"label":"myform","value":"","type":"text","validation":"{ required: true}"}}]

// Transform the array
let result = arr.reduce((res, item) => {
  // Assigning the value to the result object
  res[item.name] = item.children;
  return res;
}, {});

console.log(result);

For more information on using reduce, visit this link

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

Utilize Angular's ability to set values in line while clicking using an asynchronous function

I am facing a unique challenge where I need to assign a value to a variable inline using a click event that triggers an async function call. The scenario involves rendering a deeply nested and complex set of objects on the screen within an ng-template (e.g ...

During the test, an unexpected error occurred: Configuration file error! Module 'karma-remap-istanbul' not found

Whenever I run ng test, I keep encountering the following error message - what could be causing this issue? An unhandled exception occurred: Error in configuration file! Error: Module 'karma-remap-istanbul' cannot be found Below is the content ...

Using Typescript to typecast in D3.js

Utilizing the D3 graph example available here. I've defined my data object as shown below: interface ID3Data { age: string, population: number } const data: ID3Data[] = [ { age: "<5", population: 2704659 }, { age: "5-13", population: 4499 ...

"After updating to version 3, the Ionic 3 component's JavaScript is failing to refresh properly

During the development of my Ionic 3 app, I encountered what I believe is a cache issue. It seemed to be related to lazy loading components as the problem arose after upgrading to v3 and activating lazy loading. While in development mode and using ionic se ...

Angular 7 ng-select validation with required form control

Currently, I am utilizing the ng-select plugin for a dropdown search feature, but I am encountering issues with validation when a selection is not made from the dropdown menu. Here is how I have implemented it: <div class="form-group"> <ng-sel ...

Make sure to wait for the observable to provide a value before proceeding with any operations involving the variable

Issue with handling observables: someObservable$.subscribe(response => this.ref = response); if (this.ref) { // do something with this.ref value } ERROR: this.ref is undefined How can I ensure that the code relying on this.ref only runs after ...

Displaying Child Component in Parent Component After Click Event on Another Child Component: How to Implement Angular Parent/Children Click Events

After delving into Angular 7 for a few weeks, I find myself faced with the challenge of toggling the visibility of a child component called <app-child-2> within a Parent component named <parent>. This toggle action needs to be triggered by a cl ...

In Laravel, a post request can pass a class with a property that is of a different class type

In my Laravel controller, I have the following function: public function save(Request $request, ClientOrderDTO $clientOrderDTO){ } The definition of the ClientOrderDTO used above is as follows: use App\DTO\ClientDTO; class ClientOrderD ...

Is it possible to transfer files using Angular 2?

Currently, I am utilizing Angular2 and TypeScript to transmit a file in conjunction with JSON Data to a designated server. HTML Code <input type="file" class="form-control" name="avatar" id="uploadyour" name="uploadyour" #uploadyour="ngModel" [(ngMode ...

Encountered an npm install error: The package does not meet the peerDependencies requirements of its siblings

When I try to execute the npm install command, it throws these errors: npm ERR! peerinvalid The package @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0b3bfa2b590e7fee2fee1e5">[email protected]</a> does ...

To run multiple environments with react-native-dotenv in a React Native project using Typescript, only the local environment is activated

Currently, I am facing an issue while trying to initialize my React Native app with TypeScript in three different environments - development, local, and testing. When I attempt to run APP_ENV=testing expo start or APP_ENV=development expo start, it always ...

Tips for accessing the following element within an array using a for loop with the syntax for (let obj of objects)

Is there a way to access the next element in an array while iterating through it? for (let item of list) { // accessing the item at index + 1 } Although I am aware that I could use a traditional for loop, I would rather stick with this syntax. for (i ...

Type-constrained generic key access for enhanced security

While attempting to create a versatile function that retrieves the value of a boolean property using a type-safe approach, I encountered an issue with the compiler not recognizing the type of my value. type KeyOfType<T, V> = keyof { [P in keyof T a ...

Attempting to incorporate NestJS modules into an NX monorepo is a task that Angular is currently

Recently, I encountered a frustrating issue while working with a monorepo that contains both Angular and NestJS. In an attempt to access DTOs, I made the mistake of including NestJS files on the client side. This caused Angular compilation errors due to de ...

Creating a custom Typescript type by leveraging Javascript variables as the key identifiers

Picture a Typescript library that serves as a database interface, giving developers the ability to specify record attributes/columns/keys to be retrieved from the database. Is it feasible to return a type that includes the keys specified by the developer? ...

The angular [hidden] directive fails to function properly within a loop in a production environment

I am facing an unusual problem. In my code, I have a loop that goes through a collection and sets the [hidden] attribute based on a property value in each item of the collection. Initially, all these values are set to false. Here is how it looks: <ng-co ...

Angular 6 custom validation: Ensure that at least one textarea is completed

Is there a way for me to display an error message when the submit button is clicked and none of the textarea fields are filled out? And how can I set it up so that the submit action only renders when at least one field is completed? Looking for the best ap ...

Tips for making a oneOf field nullable using TypeScript and AJV

A field named platform exists in my code, and it can hold either a string or an array of strings (string[]). The field can also be nullable or undefined if not passed as input. TypeScript Interface export interface IEntityLeaderboardQuery { rank: stri ...

Looking for guidance on locating Typescript type definitions?

As a newcomer to Typescript, I have recently delved into using it with React. While I have grasped the fundamentals of TS, I find myself perplexed when it comes to discovering or deriving complex types. For example, in React, when dealing with an input el ...

Using observable object fields as query parameters in Firestore allows for dynamic filtering and retrieval

I have two separate services in my Angular project: an Auth service and a query service. The Auth service handles user authentication by managing the login process and observing changes to the user object. import {Injectable} from '@angular/core&apo ...