Exploring Nested JSON Iteration in Angular4

I am struggling to iterate through a nested JSON and extract the desired output. Can someone assist me in retrieving the bpmn:startEvent id value from the JSON provided below?

{  
   "bpmn:definitions":{  
      "@attributes":{  
         "xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
         "xmlns:bpmn":"http://www.omg.org/spec/BPMN/20100524/MODEL",
         "xmlns:bpmndi":"http://www.omg.org/spec/BPMN/20100524/DI",
         "xmlns:dc":"http://www.omg.org/spec/DD/20100524/DC",
         "id":"Definitions_1",
         "targetNamespace":"http://bpmn.io/schema/bpmn"
      },
      "bpmn:process":{  
         "@attributes":{  
            "id":"Process_1",
            "isExecutable":"false"
         },
         "bpmn:startEvent":{  
            "@attributes":{  
               "id":"StartEvent_1"
            }
         }
      },
      "bpmndi:BPMNDiagram":{  
         "@attributes":{  
            "id":"BPMNDiagram_1"
         },
         "bpmndi:BPMNPlane":{  
            "@attributes":{  
               "id":"BPMNPlane_1",
               "bpmnElement":"Process_1"
            },
            "bpmndi:BPMNShape":{  
               "@attributes":{  
                  "id":"_BPMNShape_StartEvent_2",
                  "bpmnElement":"StartEvent_1"
               },
               "dc:Bounds":{  
                  "@attributes":{  
                     "x":"173",
                     "y":"102",
                     "width":"36",
                     "height":"36"
                  }
               }
            }
         }
      }
   }
}

Answer №1

function findValuesByKey(data, key) {
    let results = [];
    if (!key) {
        return results;
    }

    function search(data, key) {
        Object.keys(data).forEach(function (dataKey) {
            if (typeof data[dataKey] === 'object' && !(data[dataKey] instanceof Array)) {
                if (dataKey === key) {
                    results.push(data[dataKey]);
                }
                search(data[dataKey], key);
            } else if (dataKey === key) {
                results.push(data[dataKey]);
            }
        });
    }
    search(data, key);
    return results;
}

let targetKey = 'name';

console.log(findValuesByKey(myData, targetKey));

Please note: Change the target key to search for any specific key in the data object. This function will return an array of all corresponding values.

Answer №2

var processModel = {
  "bpmn:definitions": {
    "@attributes": {
      "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
      "xmlns:bpmn": "http://www.omg.org/spec/BPMN/20100524/MODEL",
      "xmlns:bpmndi": "http://www.omg.org/spec/BPMN/20100524/DI",
      "xmlns:dc": "http://www.omg.org/spec/DD/20100524/DC",
      "id": "Definitions_1",
      "targetNamespace": "http://bpmn.io/schema/bpmn"
    },
    "bpmn:process": {
      "@attributes": {
        "id": "Process_1",
        "isExecutable": "false"
      },
      "bpmn:startEvent": {
        "@attributes": {
          "id": "StartEvent_1"
        }
      }
    },
    "bpmndi:BPMNDiagram": {
      "@attributes": {
        "id": "BPMNDiagram_1"
      },
      "bpmndi:BPMNPlane": {
        "@attributes": {
          "id": "BPMNPlane_1",
          "bpmnElement": "Process_1"
        },
        "bpmndi:BPMNShape": {
          "@attributes": {
            "id": "_BPMNShape_StartEvent_2",
            "bpmnElement": "StartEvent_1"
          },
          "dc:Bounds": {
            "@attributes": {
              "x": "173",
              "y": "102",
              "width": "36",
              "height": "36"
            }
          }
        }
      }
    }
  }
};

console.log(processModel["bpmn:definitions"]["bpmn:process"]["bpmn:startEvent"]["@attributes"].id);

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

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

What is the best way to merge strings and JMESPath queries in order to construct a webhook payload?

I'm currently exploring the use of Cloud Custodian webhooks to generate tagged events in Datadog using the Datadog API. The code snippet below is almost functional, however, the tag for account_id is not being created in Datadog. When examining the b ...

Populate UIPickerView with nested array in JSON format

Each object in the sites array of the JSON Data has its own array called "categories," structured like this: "sites": [ { "nid": "25109", "name": "guard.com", "url": "http:\/\/www.trial.com\/guard\/", "description": null, " ...

Using JSON data with an Android array

I am facing an issue with the code I have written to parse information received after sending a post request. The response looks like this: [{"fromUser":"Andrew"},{"fromUser":"Jimmy"}] My goal is to extract these users and display them in a list view. Bel ...

Are the missing attributes the type of properties that are absent?

I have a pair of interfaces: meal-component.ts: export interface MealComponent { componentId: string; componentQuantity: number; } meal.ts: import { MealComponent } from 'src/app/interfaces/meal-component'; export interface Meal { ...

Having trouble retrieving JSON data from an external source

I'm currently facing a challenge where I am unable to fetch JSON data from a webpage despite multiple attempts. I keep encountering the following errors: Uncaught SyntaxError: Unexpected token : or XMLHttpRequest cannot load URL. No 'Access-Co ...

Exploring the Incorporation of String as a Component Identifier in React and TypeScript

My input component can render either a textarea component (from a library) or a regular input. Check out the code below: import React, { useEffect, useRef, useState } from 'react' import './AppInput.css' interface Props { placehold ...

Web API OData failing to retrieve accurate metadata

I am currently utilizing OData v4 in conjunction with Web API to interact with my AngularJS web application. Specifically, I am attempting to showcase my data using Kendo UI Grid. The issue I'm encountering is that the metadata returned by my Web AP ...

How to configure mat-sort-header in Angular Material for mat-table

My current table is created using Angular Material: <mat-table *ngIf="!waiting" class="table-general table-summary" #table [dataSource]="dataSource" matSort> <mat-header-row class="header_row" *matHeaderRowDef="headerKeys"></mat-header ...

Unexpected TypeError when using Response.send()

Here is a snippet of my simple express code: const api = Router() api.post('/some-point', async (req, res, next) => { const someStuffToSend = await Promise.resolve("hello"); res.json({ someStuffToSend }); }) In my development environmen ...

The Ultimate Guide to Converting Strings into Associative Arrays in PHP

I need help converting a specific string into a proper associative array. To view the string data, please click on the following link: https://maps.googleapis.com/maps/api/geocode/json?latlng=16.539311299999998,80.5820222 The desired outcome is to conve ...

Error: Component fails to compile when imported via a module in TestBed

Struggling to write unit tests for a component that includes another component tag in its HTML. <bm-panel [title]="title" [panelType]="panelType" [icon]="icon" class="bm-assignment-form-panel"> <div *ngIf="isLoading" class="bm-loader"> ...

Error encountered during Angular upload using Asp.net core: System.Text.DecoderFallbackException is thrown when bytes [FF] cannot be translated at the specified index

I am having trouble uploading a file using Angular 7 and Asp.net core 2.2 I have set up the Angular web service to append the file and include a property Name. However, when I call the WebService from Angular, I encounter an error in the Asp.net core l ...

Higher order components enhance generic components

I'm facing an issue where I want to assign a generic type to my React component props, but the type information gets lost when I wrap it in a higher order component (material-ui). How can I ensure that the required information is passed along? type P ...

What is the reason for Google Chrome extension popup HTML automatically adding background.js and content.js files?

While using webpack 5 to bundle my Google Chrome extension, I encountered an issue with the output popup HTML. It seems to include references to background.js and content.js even though I did not specify these references anywhere in the configuration file. ...

Retrieve JavaScript functions as JSON or text in AngularJS and execute them

Currently, I am working on developing an AngularJS application and have come across a particular challenge that needs to be addressed: After making a web service call, I receive JavaScript code that looks like this: { "script":"function foo(a, b) { c = ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

Converting JSON to Array: A Step-by-Step Guide

Greetings, StackOverflow community! This is my inaugural question here. I believe the answer is not overly complex, but my knowledge of Javascript is quite rudimentary. Currently, I have a JQuery AJAX function that processes this JSON object: { "Users" ...

Mapping an Optional<Enum> with @RequestBody in Spring's MVC

I am working on a rest controller that includes the following method: @RequestMapping(value = "", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<?> add(@Valid @RequestBody MyModel myModel, ...

Tips for utilizing the onClick handler when mapping through items in React

Currently, I am a student learning about react. During the course of working on a project, I encountered a problem that left me with a question. {pages.map((page, idx) => ( <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}> < ...