The technique for accessing nested key-value pairs in a JSON object within an Angular application

After receiving the response from the backend, I have retrieved a nested hash map structure where one hash map is nested within another:

hmap.put(l,hmaps); //hmap within hmap

When returning the response to the frontend, I am using the ResponseEntity method to send back the data in the following format:

The structure of the response obtained from the Backend is as follows:

In this structure, 'email1' and 'email2' act as keys for a main hash map, with their corresponding subparts being key-value pairs within the nested hash map.

responsive: {email2: {,…},…}
 email1: {sub3: "Hi Subpart 3", sub4: "Hi Subpart 4",…}
  sub1: "Hi subpart 1"
  sub2: "Hi subpart 2"
  sub3: "Hi Subpart 3"
  sub4: "Hi subpart 4"
 email2: {,…}
  sub7: "Hi Subpart 7"
  sub8: "Hi Subpart 8"

To access 'email1' and 'email2' in my code, I have utilized the following approach:

 Object.keys(emails.responsive).forEach(e => {
          let ref = this.dialog.open(emaildialog, {    
             data: emails.responsive[e],
             width: "600px",
             height: "600px",

            } 
          );

        });

However, I am currently facing difficulties in accessing the individual subparts of each Email type.

Answer №1

If you have structured data like this:

 messages = {
  message1: {
    part1: "Hello part 1",
    part2: "Hello part 2",
    part3: "Hello Part 3",
    part4: "Hello part 4",
  },
  message2: {
    part5: "Hello part 5",
    part6: "Hello part 6",
    part7: "Hello Part 7",
    part8: "Hello part 8",
  }
}

You can access each part of every message by doing the following:

Object.keys(messages).forEach(m => {
  Object.keys(messages[m]).forEach(item => {
    console.log(messages[m][item]);
  })
})

Answer №2

when dealing with the given JSON structure or nested JSON:

    Obj : {
      email1: {
        sub1: "Hi subpart 1",
        sub2: "Hi subpart 2",
        sub3: "Hi Subpart 3",
        sub4: "Hi subpart 4",
      },
      email2: {
        sub5: "Hi subpart 5",
        sub6: "Hi subpart 6",
        sub7: "Hi Subpart 7",
        sub8: "Hi subpart 8",
      }
    }

or

    Obj : {
      email1: {
        sub1: "Hi subpart 1",
        sub2: "Hi subpart 2",
        sub3: "Hi Subpart 3",
        sub4: {
            sub41: "Hi Subpart 4",
            sub42: "Hi Subpart 42"
        },
      },
      email2: {
        sub5: "Hi subpart 5",
        sub6: "Hi subpart 6",
        sub7: "Hi Subpart 7",
        sub8: "Hi subpart 8",
      }
    }

explore the following:

  function getObjectKeyValue(obj, key) {
      if (typeof(obj) === "string")
        console.log(key + " " + obj);

      else for (key in obj)
        getObjectKeyValue(obj[key], key)
    }

getObjectKeyValue(Obj)

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

Error: Attempting to access the 'getProvider' property of an undefined variable

I am encountering an error that says "property of undefined (reading getProvider)" while deploying my function to Firebase. I am currently trying to figure out how to obtain the auth instance. When I attempt to use firebase.auth, it results in another er ...

The difference between emitting and passing functions as props in Vue

Imagine having a versatile button component that is utilized in various other components. Instead of tying the child components to specific functionalities triggered by this button, you want to keep those logics flexible and customizable within each compon ...

Integrating objects into the <select> element through the combination of C#, JavaScript, and HTML connected to a SQL

Can someone assist me in resolving this issue? I am trying to populate an HTML element with database fields using C# and JavaScript, but so far my code is not producing any output. I have also attempted to include a button that calls the "loadGrp" function ...

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

What could be causing jQuery animate to malfunction on mobile devices when a viewport is present?

Everything seems to be working fine on my desktop webpage, but when I try it on mobile, there is no scroll... $("HTML, BODY").animate({ scrollTop: 500 }, 1000); This post suggests that mobile devices may not scroll on the body, but on the vi ...

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...

Encountering an issue with unexpected token 'import' while working on Angular-cli and RC

Currently, I'm in the process of setting up Material 2 with Angular-cli RC5. However, when attempting to load the material button component in app.module.ts, I encounter the following error message. zone.js:461 Unhandled Promise rejection: SyntaxErro ...

Messing with onBeforeUnload causes issues with the browsing history in Angular

After the user finishes entering data on a page, my goal is for them to return to the previous page (e.g. Main Page -> Input Page). If I redirect them when they click submit, it creates a circular history loop (Main Page -> Input Page -> Main Page). Theref ...

The checkValidity function fails to identify incorrect "tel" input

In my form, I am using the checkValidity function to validate inputs. However, I have encountered an issue where the validation only works when an input with the required attribute is missing a value. It doesn't work if there is a value type mismatch, ...

Replace Nebular theme with a new design for a single component

I am currently using Nebular in my Angular application and I am trying to figure out how to customize the theme settings for a specific component on just one page, without affecting other instances of the same component that are using the default settings. ...

What is the method for retrieving the name of an object's property within an Angular template

I am trying to display the name of a nested object's property using Angular interpolation <ng-container ngFor="let item of saleDetailsAggegater.productMap | keyvalue"> <tr *ngFor="let qtyMap of item.value | keyvalue"&g ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

Exploring ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data: {"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06 ...

When implementing `useRouter().push()` in Next.js, it has the ability to refresh

I have recently started using a custom node server in my Next.js app. Previously, useRouter().push() was working fine without a custom server and providing a seamless single-page app experience. However, with the custom server, it now refreshes my applicat ...

Exploring the concept of JavaScript closures and the pitfalls of name clobber

Is it possible for variables defined inside an inner function with the same name as a variable in an outer function to be isolated from the outer variable? function() { var myTest = "hi there"; ( function( myLocalTest ) { myLocalTest = "go ...

My goal is to eliminate the console error message "@ Angular: GET http://localhost:4200/assets/i18n/1/fr.json 404 (Not Found)" related to missing file

Is there a way to prevent the "GET http://localhost:4200/assets/i18n/1/fr.json 404 (Not Found)" error from appearing in both the console and network of the browser while using Angular? I need a solution for this.custom.translate.loader.ts****** return Obse ...

Javascript encountering issues with recognizing 'self.function' within an onclick event

Recently, I have been working on enhancing a Javascript file that is part of a Twitter plugin. One of the key additions I made was implementing a filter function for this plugin. Here is a snippet of the script showcasing the relevant parts: ;(function ( ...

Set up Nginx to host Angular static files and act as a reverse proxy for express

Recently, I've started using Nginx for serving static Angular files and proxying to a backend Express server. Both the frontend (with Nginx) and backend are dockerized. My frontend consists of a button that makes a request to fetch data from Express. ...

Challenge encountered when utilizing angular 2 RC router for programmatic route navigation

Currently, I am utilizing the RC router in version rc1 with two defined routes as shown below: @Routes([ {path: '/', component: HomeComponent}, {path: '/signin', component: SigninComponent}, {path: '/dashboard', c ...

Tips for delaying the execution of numerous ajax success callbacks?

In my JavaScript code, I am facing the following situation: call_A(success_A) call_B(success_B) function call_A(success){ // make ajax request success(result) } function call_B(success){ //make ajax request success(result) } function success_A(){ ...