Navigating through Objects in Angular 9

I am facing a challenge in Angular 9/Typescript while trying to iterate through the object response from my JSON data. Despite searching for solutions, I haven't found any that work for me. In my JSON, there is a section called "details" which contains sub-sections like "personal details", "work details", and "phone number". My goal is to extract each node within these sections dynamically in order to create a dynamic form. Any help would be greatly appreciated.

Note: I am attempting to achieve this using a function in .ts rather than utilizing *ngFor.

"details":
{
  "personalDetails":
  {
    "title" :"Personal Details",
    "fields":
    [
      {
        "label":"First Name",
        "type":"text",
        "validation":
        {
          "required":true
        }
      },
      {
        "label":"Last Name",
        "type":"text",
        "validation":
        {
          "required":true
        }
      }
    ]
  },
  "workDetails":
  {
    "title" :"Work Related Details",
    "fields":
    [
      {
        "label":"Company Name",
        "type":"text",
        "validation":
        {
          "required":true
        }
      },
      {
        "label":"Date Of Joining",
        "type":"date",
        "validation":
        {
          "required":true
        }
      }
    ]
  },
  "phoneNumberDetails":
  {
    "title" :"Phone Number Details",
    "fields":
    [
      {
        "label":"Primary Contact",
        "type":"number",
        "validation":
        {
          "required":true
        }
      },
      {
        "label":"Secondary Contact",
        "type":"number",
        "validation":
        {
          "required":false
        }
      }
    ]
}

Answer №1

To loop through an object, use the <code>Object.keys(result).forEach((key)=>{ const value = result[key]; })
method.

I have created a StackBlitz demo to demonstrate how it is done.

Check out the example here!

Answer №2

userData = {
  info: {
    personalInfo: {
      title: "Personal Information",
      attributes: [{
          label: "First Name",
          type: "text",
          validation: {
            required: true
          }
        },
        {
          label: "Last Name",
          type: "text",
          validation: {
            required: true
          }
        }
      ]
    },
    professionalInfo: {
      title: "Work Details",
      attributes: [{
          label: "Company Name",
          type: "text",
          validation: {
            required: true
          }
        },
        {
          label: "Date Of Joining",
          type: "date",
          validation: {
            required: true
          }
        }
      ]
    },
    contactInfo: {
      title: "Contact Details",
      attributes: [{
          label: "Primary Contact",
          type: "number",
          validation: {
            required: true
          }
        },
        {
          label: "Secondary Contact",
          type: "number",
          validation: {
            required: false
          }
        }
      ]
    }
  }
};

// Extracting and displaying data from the object properties
for (let key of Object.keys(userData.info)) { 
  let item = userData.info[key];
  console.log(item.title);
  console.log(item.attributes);
}

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

The ReactJS Application Cache Client fails to display the most recent updates

One issue I'm currently facing is with my application in production. Some clients have reported that they are unable to see the new changes unless they clear their cache completely. Using Techs: React Any suggestions on what steps I should take to a ...

White Background Dialog in Angular

I am struggling to change the default white background of my webpage. Is there a way I can use CSS to blur or darken the background instead? I tried applying CSS code but couldn't locate the correct class. I also attempted setting the "hasBackdrop" at ...

Issue with Angular 6 and Html Webpack Plugin

My project was recently updated from Angular 5 to Angular 6, causing some changes in the file structure. The webpack.config files are no longer present and the project now operates under CLI engage. However, I encountered an issue after the migration rela ...

Problem with the Auto-fill Feature in PrimeNG Module

Check out my code on Gist:   https://gist.github.com/rickymuvel/8ddc4d14d90877329447ddde9c0aa835 The issue I'm facing involves the Autocomplete module in PrimeNG. It seems that the specific path in the ubigeo.service.ts file is not being called. Her ...

What is the best way to assign a value to a button in Ionic/Angular?

Is there a way to bind the name and value attributes to a button? I am facing an issue with this and need a solution. I am attempting to achieve the following: <ion-button type="submit" color="primary" style="text-align:center& ...

Unable to bring in openai on Node.js

I recently installed Node version 16.13.1 and globally installed the openai package using 'npm install -g openai'. In my script, I imported the necessary packages like this: const { Configuration, OpenAIApi } = require('openai') Howeve ...

Methods to acquire the 'this' type in TypeScript

class A { method : this = () => this; } My goal is for this to represent the current class when used as a return type, specifically a subclass of A. Therefore, the method should only return values of the same type as the class (not limited to just ...

Are there any tools available that can convert ThreeJS code into WebGL?

Are there any existing tools that can convert ThreeJS to WebGL? Or, could you provide guidance on creating a converter for ThreeJS to WebGL? ...

Vue automatically clears the INPUT field when disabling it

Have you ever noticed why Vue resets a text input field when it's set to disabled? This behavior is not observed with plain Javascript and also doesn't affect textarea fields. var app = new Vue({ el: '.container', data: { disab ...

Ordering in D3 Code

I'm struggling with understanding the correct structure for writing D3 code. For example: In the code snippet below, I noticed that if I place the 3rd section (Chart Title) of the code after creating the svg element, the title text doesn't displ ...

Using generics in Typescript, transform an array of strings into various types and values

Enhanced with coding norms I have obtained an array of fruit values: const fruitsArray = ["apple", "banana", "peach"] as const; Utilizing this array as a foundation, I generated types and values in the following manner: type ...

The dispatch function in redux-thunk is not functioning as expected

Having trouble with thunk and async dispatching? Check out this code snippet: function fetchProvider() { return (dispatch) => { graphqlService(fetchProviderQuery) .then((result) => { dispatch({ type: FETCH_PROVIDER, ...

Swipe to eliminate an element in Ruby on Rails

I am looking to implement a drag-and-drop delete feature on my website, similar to the recycle bin/trash function on Windows or OSX. Within my database, I have multiple objects represented by div elements using Ruby. While I know how to add drag functiona ...

Encountering issue with jQuery - Ajax causing error 500 for select posts

Recently, I encountered an issue with the Ajax functionality on a live website. It was previously working perfectly fine, but suddenly started returning a 500 internal server error instead of the expected page. Oddly enough, I discovered that I could stil ...

"Expo Securestore is encountering an issue where it is unable to store the user ID and token following authentication

I am currently working on securely storing the userId and token in SecureStore. I have successfully retrieved the token from SecureStore on the next screen, but for some reason, I am unable to see the userId. const doUserLogIn = async() => { try { ...

What is the best way to create a line break in a flex div container to ensure that overflowing items wrap onto the next line using

Using material-ui popper to display a list of avatars. Trying to arrange the avatars horizontally within the popper. <Popper style={{ display: 'flex', maxWidth: '200px', }}> <div style={{ marginRight: '20px' }}&g ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...

Having trouble retrieving data through AJAX requests

My goal is to verify the existence of a user email on "blur()" using AJAX to send textbox data to PHP. Even though I can see the posted data in Firebug, I keep encountering an error: Undefined index: data. Despite numerous attempts, I have been unable to r ...

When the admin clicks the start button, redirect all users to the designated page

Currently, I am developing a voting application that features both an admin and users. My goal is for the voting campaign to kick off as soon as the admin clicks on the start button. Upon starting the voting process, I aim to redirect all users to a diff ...

Is the value of the incorrect store ref in Vue3 being altered?

Welcome to the store: import { ref } from "vue"; // Storing all the country data export const countriesData = ref(); export const isLoading = ref(true); async function fetchData() { try { isLoading.value = true; const respon ...