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

Ways to dynamically display or hide content in Angular 7

>when an English button is clicked, its corresponding div should be shown. If another button is clicked, its div should also show without closing the previous one. I want each div to close only when its respective button is clicked again. >Please not ...

Creating columns on the fly within a row

I would like to create a layout where images are displayed in one row, but if the screen size changes, I don't want them to wrap and display below. Instead, I want to show a button that redirects to another page. I'm not sure how to achieve this. ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Unable to transfer props object to React component using TypeScript

Apologies if this seems like a basic issue, but I've been struggling with it for the past two days. I'm currently working on writing a simple unit test in Vitest that involves rendering a component to the screen and then using screen.debug(). The ...

Having difficulties in TypeScript identifying types within a project containing multiple node_modules directories

I am currently in the process of transitioning a codebase from Flow to TypeScript. I am encountering an issue with the error message Cannot find module 'SOME DEPENDENCY' or its corresponding type declarations.ts(2307) for several dependencies tha ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Discovering necessary information by iterating through JSON

Being new to vue js, my goal is to loop through the provided JSON data and check if the required data is present within the file. Here is a snippet of the JSON: [ { "id": "text-5", "widget": "hello", "params": { "0": "section-right", ...

What is the best way to associate and merge lists from one object to another object using unique identifiers?

I have a task that involves extracting information from two JSON files. The goal is to log the names from one file and for each name, list the corresponding titles from the other file. The connection between the two files is made using an ID, although one ...

Encountering difficulty in retrieving value through the get method, resorting to interpolation. The value from the getTitle() method for 'this._title' is not being displayed

import { Component } from '@angular/core'; @Component({ selector: 'courses', template: '<h1>{{ getTitle() }}</h1>' ////issue with not displaying 'this._title' value??? }) export class CoursesCo ...

Tips for indicating errors in fields that have not been "interacted with" when submitting

My Angular login uses a reactive form: public form = this.fb.group({ email: ['', [Validators.required, Validators.email]], name: ['', [Validators.required]], }); Upon clicking submit, the following actions are performed: ...

Accessing location information using jQuery from Google's Geocoding API

Recently, I've been delving into the realm of Google Maps Geocoding and attempting to comprehend how to decipher the JSON data that it transmits back. This snippet showcases what Google's response looks like: { "results" : [ { ...

Having trouble accessing a parsed JSON value in Node.js, encountering 1 error

Currently, I am working on creating a simple news web application as a way to practice utilizing APIs. The particular API that I have chosen for this project is . If you take a look at this JSON object that I am attempting to console.log, you will see the ...

Visual Studio is refusing to highlight my code properly, intellisense is failing to provide suggestions, and essential functions like go to definition are not functioning as expected

Due to a non-disclosure agreement, I am unable to share any code. However, I am experiencing an issue with Visual Studio not highlighting my code or allowing me to utilize its built-in tools. While I can rebuild the project, I cannot edit or access any fil ...

Error encountered in Angular: FormBuilder provider not found

I am currently utilizing Angular 9. An error that I am encountering is as follows: No provider for FormBuilder This issue has been documented in numerous instances, with the common solution being to include the FormsModule in the app.module.ts file. F ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

The proper method for specifying contextType in NexusJS when integrating with NextJS

I am currently facing a challenge while trying to integrate Prisma and Nexus into NextJS. The issue arises when I attempt to define the contextType in the GraphQL schema. Here is how I have defined the schema: export const schema = makeSchema({ types: [ ...

Checkable Ionic Table

I'm curious about achieving a similar functionality to this example using Angular and Ionic, but without relying on jQuery. Here is the link for reference: Any advice on how to accomplish this would be appreciated. Thank you. ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

Developing Custom Methods with TypeScript Factories - Step 2

Working in a factory setting, I find myself needing to incorporate custom methods at some point. Thanks to the valuable input from the community, I've made progress towards my goal with this helpful answer, although I'm required to include a see ...

Echarts - Interactive line graph showcasing real-time data from Json source

Currently, my goal is to create a timeline chart with multiple lines where the number of lines varies based on the JSON data provided. The JSON data I am receiving is outlined below. I aim to plot each line for every product. How can I manipulate the dat ...