What is the best way to access the elements nested within an array of objects if the specific object key is unknown?

I am working with an array of objects, each containing a nested object like the examples below.

[{
    "-KzbaPS3vuZTG2LbuB3j": {
        "age": "24",
        "branchname": "columbia",
        "city": "hyd",
        "date": 1511418820987,
        "gender": "M",
        "id": "rcjcx8",
        "mobile": "9898989898",
        "name": "Patient1",
        "op": 100
    }
}, {
    "-KzTh7RTtTWviL4HkHv0": {
        "age": "21",
        "branchname": "kims",
        "city": "vizag",
        "date": 1511334303070,
        "gender": "F",
        "id": "45krxb",
        "mobile": "9898989898",
        "name": "aruna",
        "op": 100
    },
    "-KzTiCIheMPJIpJhPXQJ": {
        "age": "22",
        "branchname": "kims",
        "city": "hyderabad",
        "date": 1511420593865,
        "gender": "F",
        "id": "c7iqws",
        "mobile": "9878787878",
        "name": "vineesha",
        "op": 100
    },
    "-KzTnzLnRsdFWg-m5b9U": {
        "age": "26",
        "branchname": "kims",
        "city": "bheemavaram",
        "date": 1511420593865,
        "gender": "F",
        "id": "ujtgz",
        "mobile": "9876787898",
        "name": "Madhavi",
        "op": 100
    }
}]

If the specific key for the nested object is unknown, how can all the objects within the objects be extracted and stored in an array?

Answer №1

Here is a simple way to iterate through an array in JavaScript:

array.forEach(item => {
    let key = Object.keys(item)[0];
    let value = item[key]; 
    // value = { "age": "21", "id": "rcjcx8" ...} for the first element
});

Answer №2

If you're comfortable using Lodash, try implementing the code snippet below:

// Create a variable named "data" and store some data in it

let flattenedData = _.flatten(data).reduce((accumulator, currentValue) => _.assign(currentValue), {});

Answer №3

To iterate through and retrieve the keys, use them to access the corresponding values. Click here for a working example

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  jsonDataKeys : any=[];

  jsonData : any =[{
    "-KzbaPS3vuZTG2LbuB3j": {
        "age": "24",
        "branchname": "columbia",
        "city": "hyd",
        "date": 1511418820987,
        "gender": "M",
        "id": "rcjcx8",
        "mobile": "9898989898",
        "name": "Patient1",
        "op": 100
    }
}, {
    "-KzTh7RTtTWviL4HkHv0": {
        "age": "21",
        "branchname": "kims",
        "city": "vizag",
        "date": 1511334303070,
        "gender": "F",
        "id": "45krxb",
        "mobile": "9898989898",
        "name": "aruna",
        "op": 100
    },
    "-KzTiCIheMPJIpJhPXQJ": {
        "age": "22",
        "branchname": "kims",
        "city": "hyderabad",
        "date": 1511420593865,
        "gender": "F",
        "id": "c7iqws",
        "mobile": "9878787878",
        "name": "vineesha",
        "op": 100
    },
    "-KzTnzLnRsdFWg-m5b9U": {
        "age": "26",
        "branchname": "kims",
        "city": "bheemavaram",
        "date": 1511420593865,
        "gender": "F",
        "id": "ujtgz",
        "mobile": "9876787898",
        "name": "Madhavi",
        "op": 100
    }
}];

constructor(){
  for(let arr of this.jsonData){
       Object.keys(arr) && Object.keys(arr).map((key)=>{
          console.log("push")
          this.jsonDataKeys.push(key);
        });
    }
}

}

This is the HTML file:

{{jsonDataKeys}}

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
<!--<div>{{jsonData | json}}</div>-->

 <div *ngFor="let arr of jsonData">
  <div *ngFor="let item of jsonDataKeys">
    item : {{item}}
    {{arr[item] | json}}
    <br>
    <br>
  </div>
 </div>

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

Troubleshooting a VSCode and Path Error while working on an Angular Project

For the past few days, I have noticed that Intellisense in Visual Studio Code has stopped underlining incorrect file paths in my code. When I hover over the error line, it simply displays "module '*'." https://i.sstatic.net/OVSQY.jpg How can I ...

Utilizing a unique external Bootstrap link for a specific component in an Angular 8 project

For a specific component in my Angular project, I am looking to utilize this <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> Any guidance on achieving this? (excluding index.html) ...

How can I retrieve distance data from the Google Maps API within an Angular service?

I am currently working on implementing the JavaScript version of the Google Maps API in order to resolve a CORS issue that I encountered with the regular API. Specifically, I am looking to calculate the distance and time between two destinations. How can I ...

Unable to assign decimal values to the tooltip value in Angular's Ng bar chart

I'm currently working on my Angular project with ngChartjs, and I've run into a conflict regarding the tooltip values. https://i.sstatic.net/NBKCJ.png For example, if the value is 6131327.319655154, I have tried formatting it to 6131327.31 usin ...

What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript. import { Server } from "Socket.I ...

Utilizing Typescript for Axios Response

Incorporating Typescript into my project, I encountered a tedious issue while making an API call using axios. The problem lies within handling nested data properly. Despite my belief that I have correctly typed everything, I persistently face a Typescript ...

Struggling to figure out how to change the display when navigating between different routes

I've been struggling for the past 3 hours trying to switch between routes. Let me explain further: Server Template HTML: <!-- I want the first div to display when the component opens, but disappear and show router-outlet when a button is clicked. ...

Obtain the selector from the parent element

Hello everyone, I am currently working on developing a parent class called Event that will manage the DOM for four child classes: vote-event, view-event, my-events, and my-votes. The concept is to have a single HTML file, a parent Component, and four chi ...

Get the HTML content from a component that has been imported

Is it possible to access the HTML content of an imported component in Ionic2/Angular2? For instance: import {A} from '../../components/a/a'; console.log(A.html()); I am looking for a way to achieve something similar to this - even though ther ...

What is the reason behind the inability to access a static member in a property method, but being able to access it

Why is it an issue to access a static member from a property method in TypeScript? This behavior works fine in plain ES6 and as a proper prototype method. class FooBar { static v = 123; static foo = () => this.v; // this throws an error in TS ...

Stop unauthorized access to a lazy-loaded module through direct routes

Within my application's structure, I utilize the MasterModule to load the MasterComponent along with its child routes. Among these child routes is one that lazy loads my EquipmentSLModule: master-routing.module.ts: const routes: Routes = [ { p ...

Ensuring the presence of TypeScript variables

Take a look at this code snippet: let str: string | null; function print(msg: string) { console.log(msg); } print(str); When running this code, the typescript compiler correctly identifies the error, stating that Argument of type 'string | nu ...

Declaration of function with extra attributes

Is there a way to define a type for a function that includes additional properties like this? foo({ name: 'john' }) foo.type I tried the following solution, but TypeScript seems to think that foo only returns the function and cannot be called wi ...

Safari 11.1 and Angular 9 - config object missing a defined key-value

While using Safari, I have encountered a problem in the Primeng input text field. When I type into the text box, errors are logged into the console. handleKeypress — injected.entry.js:8231TypeError: undefined is not an object (evaluating 'settin ...

When it comes to utilizing BehaviorSubject.value and AsyncSubject in RXJS, it is essential to understand

As a newcomer to RXJS, I am seeking advice on whether my current approach is considered best practice. My situation involves an API that returns a list of countries which needs to be utilized across multiple components. The external API can sometimes be sl ...

Setting the current date in Angular using TypeScript and storing it in a MySQL database

As I delve into learning Angular, I am focused on practicing with a form. Specifically, I am attempting to include the current date when inputting client records along with their RFC, branch, and cost. Unfortunately, my attempts have been unsuccessful in i ...

Error encountered during the deployment of Ionic 3 with TypeScript

After completing the development of my app, I ran it on ionic serve without any issues. However, when compiling the app, I encountered the following error message. Any assistance in resolving this matter would be greatly appreciated. [15:40:08] typescri ...

Ways to retrieve dictionary keys as an array in Angular

Here is an example of an Angular dictionary: { ARRAY1: [{...}, {...}, {...}] ARRAY2: [{...}, {...}, {...}] ARRAY3: [{...}, {...}] ARRAY4: [{...}] } I want to show all the keys of arrays from this dictionary on an HTML page. I attempted to do ...

Waiting for an observable to load the page in Ionic 2

When loading a page that calls an API to fetch objects for display, I encounter an issue where the page finishes loading before any data is received, resulting in an empty display. constructor(public navCtrl: NavController, public userData: UserData, publ ...

Exploring the usage of asynchronous providers in NestJS

I am currently utilizing nestjs and I am interested in creating an async provider. Below is my folder structure: . ├── dist │ └── main.js ├── libs │ └── dma │ ├── src │ │ ├── client │ ...