Exploring the Depths of JSON Arrays within Typescript

I am faced with a challenge in extracting the value of the "id" from the following array of JSON data. The issue lies in the fact that the value is enclosed within double square brackets "[[" which are causing complications in retrieving the desired result. Furthermore, I have observed that when the array of JSON is generated through a loop, it sometimes results in single "[" brace and other times in "[[" braces...

[  
   [  
      {  
         "attributes":{  
            "id":"Task_1yett21"
         },
         "incoming":"SequenceFlow_112bxv0",
         "outgoing":"SequenceFlow_1gkdhq3"
      },
      {  
         "attributes":{  
            "id":"Task_0i5lteb"
         },
         "incoming":"SequenceFlow_1gkdhq3",
         "outgoing":"SequenceFlow_1gjii2n"
      },
      {  
         "attributes":{  
            "id":"Task_1v37yfe"
         },
         "incoming":"SequenceFlow_1gjii2n",
         "outgoing":"SequenceFlow_0bygyft"
      }
   ]
]

In order to extract the JSON objects from the above array, I have implemented a function as shown below...

var getAllValuesOfKey = function (dataObj, queryKey) {
      var resultArr = [];
      if (!queryKey) {
          return resultArr;
      }

      function execute(dataObj, queryKey) {
          Object.keys(dataObj).forEach(function (key, index) {
              if (typeof dataObj[key] == 'object' && !(dataObj[key] instanceof Array)) {   
                  if (key == queryKey) {
                      resultArr.push(dataObj[key]);
                  }
                  execute(dataObj[key], queryKey);
              } else if (key == queryKey) {
                  resultArr.push(dataObj[key]);
              }
          });
      }
      execute(dataObj, queryKey);
      return resultArr;
  } 
  var searchKey = 'task';
  var result=getAllValuesOfKey(obj1, searchKey);

Answer №1

To access the inner array within your loop, simply use index 0 of the outer array. Here's an example:

let myDoubleArray: any = [[{...}, {...}, {...}]];
for (let i = 0; i < myDoubleArray[0].length; i++) {
  console.log(myDoubleArray[0][i].attributes.id);
}

If your arrays are still in JSON format, you'll need to convert them to JavaScript objects using JSON.parse() before iterating through the data.

Answer №2

let array = [  
   [  
      {  
        "attributes":{  
           "id":"Task_1yett21"
        },
        "incoming":"SequenceFlow_112bxv0",
        "outgoing":"SequenceFlow_1gkdhq3"
     },
     {  
        "attributes":{  
           "id":"Task_0i5lteb"
        },
        "incoming":"SequenceFlow_1gkdhq3",
        "outgoing":"SequenceFlow_1gjii2n"
     },
     {  
        "attributes":{  
           "id":"Task_1v37yfe"
        },
        "incoming":"SequenceFlow_1gjii2n",
        "outgoing":"SequenceFlow_0bygyft"
     }
  ]
]

for (let ind in array[0]) {
  //array[0][ind].attributes.id will show the id
  console.log(array[0][ind].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

Error message from Angular development server: Channel is reporting an error in handling the response. The UNK/SW_UNREACHABLE options

After recently installing a new Angular app, I encountered an issue while running 'ng serve'. The application initially loads without any problems, but after a few seconds, I started seeing a strange error in the console. Channel: Error in handle ...

Looking to transform this PHP function into a jQuery function that generates all the possible combinations of values in an array?

I stumbled upon this PHP code on a programming forum. Here's the original code snippet: function everyCombination($array) { $arrayCount = count($array); $maxCombinations = pow($arrayCount, $arrayCount); $returnArray = array(); $conve ...

Angular 2 is throwing an error stating that the argument 'ElementRef' cannot be assigned to the parameter 'ViewContainerRef'

I'm developing an Angular 2 application with angular-cli, but when I include the following constructor, I encounter the following error: Error Argument of type 'ElementRef' is not assignable to parameter of type 'ViewContainerRef&apos ...

Is it possible for a table row's cell to determine the value of the cell in the row above it?

Let me illustrate my issue with an example. Consider the following table: <table> <tr> <th>First</th><th>Second</th><th>Third</th> </tr> <tr> <td>A</td><t ...

Angular's Enhanced Feature: Selecting Multiple Columns

Looking for an open-source Angular library that can display items in multiple columns rather than each item spanning across multiple columns. Many libraries support tabular display, but the challenge is to find one that arranges items in multiple columns. ...

Angular input box with integrated datepicker icons displayed inside

Currently, I have an input field and a datepicker displayed in a row. However, I need to show an icon inside the input box instead. Here is my code: <div class="mb-2" style=" float: left;" class="example-full-width" class= ...

Differences between Angular services and exportsIn Angular,

I have a collection of straightforward tool functions that do not require sharing state across the application, do not need to be singleton instances, and do not rely on injected services. Is there any benefit to using an injectable service like: @Inject ...

What is the best way to organize and sort mysql data without disrupting operations?

I've been searching for information on this topic but haven't been able to find a tutorial that explains exactly what program to use. I have a MySQL database with expenses data. What I need is for the system to automatically categorize a new ex ...

Looking to fill every space? Try using React with MUI Grid!

I am currently using Material UI Grid to create an image grid, and I am facing challenges in eliminating the gaps between certain grid items. Despite attempting to modify the alignitems and justify values of the container, I have not been successful in r ...

What causes my scene to appear black until OrbitControl is activated in ThreeJS?

What causes the scene in ThreeJS to only appear after clicking and moving the cursor? The page remains black until I interact by clicking and moving, then everything shows up. I'm stumped on what the issue could be. Any assistance would be greatly ap ...

Executing a command efficiently in Javascript with the get method

The command that needs to be sent to the embedded device is in the form of a GET method. However, the value continuouspantiltmove: String(pt) is not being properly transmitted to the CGI script through Google Chrome, causing it to fail. Since I do not hav ...

Is it feasible to develop a TypeScript module in npm that serves as a dual-purpose tool, functioning as both a command line utility

My goal is to develop an npm TypeScript module that serves dual purposes - acting as a command line utility and exporting methods for use in other modules. The issue arises when the module intended for use as a command line utility requires a node shebang ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

Utilizing various settings using `.env` files in NodeJs

As I work on building a backend in nodejs, one of the key considerations is how to incorporate an environment configuration into the project. I am envisioning a structure where there is a /config folder housing my envparser.ts (still brainstorming a catchi ...

Error is caused by the placement of @type within the JSON object

Consider the following class structure: @XmlSeeAlso({A.class, B.class}) @XmlDiscriminatorNode("@type") public abstract class Base implements Serializable { } Let's define classes A and B: @XmlDiscriminatorValue("A") public class A extends Base { ...

Having trouble updating Angular CLI

It appears that I have successfully installed version 9 as per the usual installation process. npm install -g @angular/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9abbca8acbcaaad99ebf7e1e1f7eb"> ...

Working with nested lists in C# JSON to return data in a hierarchical structure

public class Entry { public string playerOrTeamId { get; set; } public string playerOrTeamName { get; set; } public string division { get; set; } public int leaguePoints { get; set; } public int wins { get; set; } public int losses ...

The Zip file generated in memory is experiencing corruption

I'm encountering an issue while attempting to serve a zip file generated in memory by Flask to a JavaScript front-end. However, the downloaded file appears corrupted and I am unsure of what mistake I may be making. @app.route('/route') def ...

Which one relies on the other: angular-data or angular-cache?

I'm struggling to get angular-cache set up properly. According to the documentation: Angular-cache is a dependency of angular-data and must be loaded before angular-data if you are using angular-data. That's all well and good, but what if I only ...