Retrieve the JSON information specifically for the selected ID

Having a set of JSON data, with 2 base IDs and attachment data within each ID. The goal is to click on a base ID and display its attachment data on a separate page. How can I retrieve information for the clicked ID only?

{
    "_embedded": {
        "deliveryMessageList": [
            {
                "id": "73c624c9-6db7-4fd2-ac91-c1084aee0565",
                "attachments": [
                    {
                        "id": "fb1e6d31-4c4e-4356-be5a-827ea5ec422d",
                        "attachToDeliveryMessage": false
                    },
                    {
                        "id": "160edceb-cda7-483c-a2b9-786f583b523d",
                        "attachToDeliveryMessage": true
                    }
                ]
            },
            {
                "id": "bfd600ad-754f-444d-bddb-f5cf4d7727b8",
                "attachments": [
                    {
                        "id": "e4454f8c-4ecb-444e-a82a-318bbcee1c11",
                        "attachToDeliveryMessage": false
                    },
                    {
                        "id": "791a73eb-59cc-4bba-8b16-d442169a7923",
                        "attachToDeliveryMessage": true
                    }
                ]
            }
        ]
    }
}

Presenting the UI as shown below

https://i.sstatic.net/fbPyA.png

Attempting to implement an ID to the click event for further processing

  getCustomerAccountDocs(selectedItem: any, index: number) {
    this.CustomerAccountDocsService.getCustomerAccountDocs()
    .subscribe((data: any) => {
      this.customerAccountDocs = data;
    });
  }

Below is the HTML code snippet

  <tr *ngFor="let item of customerAccountDocs; let i=index" (click)="getCustomerAccountDocs(item, i)">
    <td> {{item.accountNumber}}</td>  
    <td> {{item.id}}</td>
  </tr>

Answer №1

It seems like the key question here is how to retrieve all siblings of a specific JSON node. The method of accessing the ID may vary, but I will demonstrate a way to do it within a loop. Assuming that your main JSON object is stored in a variable named "main," you can proceed as follows:

var embedded = main["_embedded"]["deliveryMessageList"]; // or however you access the JSON keys
var newJSON = {};
embedded.forEach(data => {
    for (var key in data) {
        var currentIDsiblings = {};
        var ID = null;
        for (var subkey in data[key]) {
            if (subkey !== "id") {
                currentIDsiblings[subkey] = data[key][subkey];
            } else {
                ID = subkey;
            }
        }
        newJSON[ID] = currentIDsiblings;
    }
});

/* You can then retrieve all siblings of a specific ID by accessing newJSON[myID] */

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 presence of React Router in Office JS Excel results in a blank screen

My current project involves developing add-ins for Excel using TypeScript and React. However, I have encountered numerous challenges along the way. Unlike a typical CRA React boilerplate web application, the Office add-in behaves differently. To illustrate ...

Navigating through an array's contents with RxJs

Is there a more efficient way to iterate over an array fetched from an observable using RxJS operators in order to generate and emit new individual ListingItem objects? onGetItemData(){ this.dataService.getItemData().subscribe((itemData) => { this.it ...

Outputting double columns with Typescript Sequelize associations

I am currently in the process of constructing table models using sequelize along with typescript. Here is an example of one of my models: 'use strict'; import { Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'seque ...

Angular 2 is throwing an error, stating that Observable is not defined

I'm currently working with Observable and ChangeDetectionStrategy to notify other components about any changes that occur. However, I am encountering an issue where the Observable object addItemStream is coming up as undefined. Can anyone spot what mi ...

AG-GRID-ANGULAR - Is there a way to automatically check or uncheck a checkbox in the header component based on the status of checkboxes in the cell renderers?

Currently, I am using ag-grid for my project. In one of the columns, I have a checkbox in the header using headerComponentFramework and checkboxes in the corresponding cells using cellRendererFramework. My goal is to automatically check or uncheck the hea ...

Transforming a string such as "202309101010" into a date entity

Need to convert a string in the format "YYYYMMDDHHMM" (e.g. "202309101010") into a Date object in TypeScript? Check out this code snippet for converting the string: const dateString: string = "202309101010"; const year: number = parseInt(dateString.subst ...

Unable to utilize the useState hook in TypeScript (Error: 'useState' is not recognized)

Can you identify the issue with the following code? I am receiving a warning from TypeScript when using useState import * as React, { useState } from 'react' const useForm = (callback: any | undefined) => { const [inputs, setInputs] = useS ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

In what ways can enhancing the TypeScript type system with additional restrictions help eliminate errors?

Encountered issues while working on my TypeScript project due to errors in the type definitions of a library. The solution was to enable the strictNullChecks flag. It seems counter-intuitive that adding restrictions can eliminate errors, when usually it&a ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

Tips for sending the updated position of the marker to a function

When using the following code, the intention is to pass a dragged marker LatLng into a function in order to obtain an address. However, there seems to be an issue with this process. public LastLat : any; public LastLng : any; . . . lastLatLng(marker){ ...

JSX conditionally rendering with an inline question: <option disabled value="">Select an option</option>

Yes, I can confirm that the inline is functioning properly because in the Convert HK to Passive Segment paragraph at the top I am seeing the expected output. What I am aiming for is to display a "Choose a hotel" message when there are multiple hotels in th ...

The Vue store array declaration triggers a TS error stating that it is not assignable to a parameter of type never

I'm puzzled as to why this error keeps showing up: Argument of type '{ id: string; }' is not assignable to parameter of type 'never'. ... appearing at const index = state.sections.findIndex((section) => section.id === id); T ...

Resolving Unhandled Runtime Errors When Using Components with Dynamic API Calls in NextJS: A Guide to Fixing the Issue

As someone who is new to web development, I am currently working on a web app that makes use of the IGDB API (). The concept behind this website is allowing users to listen to game soundtracks and guess which game they belong to. For selecting a game, the ...

How to Efficiently Remove Array Elements by Index in Typescript

What is the best way to remove an item by its index using Typescript? For example: let myArray = ['apple', 'banana', 'cherry', 'date']; // How can I delete the item at index 2? ...

Transformation of entryComponents to Angular 9 Ivy

@Component({ selector: 'dynamic', template: '<ng-template *ngFor="let portal of portals" [cdkPortalOutlet]="portal"></ng-template>', // entryComponents before Ivy entryComponents: [Component1, Component2, Compone ...

How do you obtain the string name of an unknown object type?

In my backend controllers, I have a common provider that I use extensively. It's structured like this: @Injectable() export class CommonMasterdataProvider<T> { private readonly route:string = '/api/'; constructor(private http ...

Tips for ensuring that npm only creates one instance of a dependency when it is being used by multiple projects

Struggling a bit here. I am diving into npm and configuration files for the first time. The current challenge involves setting up a vue project (though it might not be directly related to the issue) with typescript and then reusing its code and components. ...

When using Webpack and Typescript together with the watch feature, an error with code TS2554 may occur only during

Software in use: webpack 4.8.3 typescript 2.8.3 ts-loader 4.3.0 Configuration for Webpack: rules: [ { test: /\.ts(x?)$/, exclude: /node_modules/, use: ['ng-annotate-loader', 'ts-loader'] }, . ...

Tailored validation for targeted field

How can I validate a partial form based on requirements? Built with Angular 7 and Clarity I have a form using the clrForm component that includes: Field 1: Name Field 2: URL Field 3: Date The form also has two buttons: Button 1: Verify Button 2: Su ...