Working with JSON data in Typescript without specified keys

My goal is to extract the IssueId from the JSON data provided below:

[
 {
  "-MERcLq7nCj5c5gwpYih":
     {"CreateDate":"2020-08-11T08:27:13.300Z","Id":"-MERcLq7nCj5c5gwpYih","IssueId":"-ME3-tuhyqlaRdZCRapj","StatusId":"2", ...},
  "-MERdViSr8oCUGsCHouS":
     {"CreateDate":"2020-08-11T08:32:15.901Z","Id":"-MERdViSr8oCUGsCHouS","IssueId":"-ME3-tuhyqlaRdZCRapj","StatusId":"3", ...},
 ...
 },
 ...
]

I am looking to retrieve the most recent status ID and parse it into an object, but I'm facing a challenge as there are no keys for me to select each item individually. I have looked at other TypeScript JSON examples, but none seem to address this specific scenario. Is there a way for me to access the content without referencing the value -MERcLq7nCj5c5gwpYih?

Answer №1

If you need to loop over an object, the for...in statement is the way to go. Check out this example:

export class AppComponent  {
  data = [
  {
    "-MERcLq7nCj5c5gwpYih": {
      "CreateDate": "2020-08-11T08:27:13.300Z",
      "Id": "-MERcLq7nCj5c5gwpYih",
      "IssueId": "-ME3-tuhyqlaRdZCRapj",
      "StatusId": "2"
    },
    "-MERdViSr8oCUGsCHouS":
    {
      "CreateDate": "2020-08-11T08:32:15.901Z",
      "Id": "-MERdViSr8oCUGsCHouS",
      "IssueId": "-ME3-tuhyqlaRdZCRapj",
      "StatusId": "3"
    }
  }
]

  ngOnInit(){
    const obj = this.data[0] // Assuming one object inside array
    for (const property in obj) {
        console.log(obj[property].CreateDate)
        console.log(obj[property].StatusId)
    }
  }
}

Learn more about the for..in statement here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Answer №2

If you wish to extract the keys of an object and loop through them to access specific properties, you can utilize `Object.keys` as shown in the example below:

const data = [{
  "1": {
    "name": "John",
    "age": 30,
    "city": "New York"
  },
  "2": {
    "name": "Jane",
    "age": 25,
    "city": "Los Angeles"
  }
}]

const targetObj = data[0]
const objKeys = Object.keys(targetObj);
console.log(objKeys) 
//[
//  "1",
//  "2"
//]

objKeys.forEach(key => console.log(targetObj[key].name)) // accessing property by key
// John
// Jane

Answer №3

When dealing with nested objects, consider the following example:

var nestedObjects={
  "-M123ABC456":
     {"CreateDate":"2021-05-20T12:45:30.200Z","Id":"-M123ABC456","IssueId":"-XY789DEF","StatusId":"2", ...},
  "-N987XYZ321":
     {"CreateDate":"2021-05-20T12:50:40.500Z","Id":"-N987XYZ321","IssueId":"-XY789DEF","StatusId":"3", ...},
 ...
 }

To access nested objects dynamically, you can use the following method:

Object.keys(nestedObjects).forEach(key => {
   var dynamicObject=nestedObjects[key];

   // Access the desired properties:
   console.log(dynamicObject.CreateDate);
   console.log(dynamicObject.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

Display Material UI icons as markers within Highcharts

Does anyone know how to use Material UI icons as markers in rendering? I have been searching for documentation but can't seem to find a clear explanation. Any guidance would be greatly appreciated! ...

What is the best way to retrieve specific information by passing multiple parameters at the end of a URL?

In my application, I am utilizing rails 4.2. Displayed below is the index action from my Descriptions Controller. def index @descriptions = Description.all if name = params[:name] description = @descriptions.where(name: name) render json: des ...

Retrieve the chosen option from a dropdown list in Angular by utilizing reactive forms

I am facing an issue where I need to pass a hard coded value from a dropdown along with the input field values in my form. The problem arises because I am using formControlName to capture the input field values, but since there are no input fields in the d ...

When conducting unit testing in Angular, it is important to avoid calling the Angular service if the return type is an observable of any when dealing

Using the Spyon function to mock a method call on a service and return an observable of 'TEST'. This method is for a service. Although similar methods with a class object return type are working fine in the debugger, there seems to be an issue wi ...

Error: script took too long to execute, no response received within 11 seconds

During my integration test, I encountered an error message saying Failed: script timeout: result was not received in 11 seconds To investigate further, I navigated to the Chrome browser performance tab and noticed several yellow indicators showing scripti ...

Transform a text received from a web service into a JSON array

After trying to convert this web service string to a JSONArray, I encountered some issues even though I had already validated it. [ { "hireDate": null, "homePhoneNumber": null, "gender": null, "city": null, "mobileNumber": null, "idNumber": 123, "religio ...

How can I incorporate an interface and specify a particular type as the return value in TypeScript?

interface Inter{ str:string } function func(){ let v:Inter={ str:'abc' }; return v; } func()//Is there a way to ensure that the type of value returned from `func` is {str:'abc'} without explicitly declaring it i ...

Creating an object type that accommodates the properties of all union type objects, while the values are intersections, involves a unique approach

How can I create a unified object type from multiple object unions, containing all properties but with intersecting values? For example, I want to transform the type { foo: 1 } | { foo: 2; bar: 3 } | { foo: 7; bar: 8 } into the type {foo: 1 | 2 | 7; bar: ...

Unable to upload JSON document into MongoDB collection using the Node driver

I've been working on a project where I need to read files from my disk and insert them into MongoDB collections. However, I'm encountering an issue where the connection is closing before the task is completed, resulting in the error message: Mong ...

Opening a modal in Angular2+ when selecting an item from ngx-chips (tag-input)

I need to implement a functionality where clicking on a tag in a dropdown should trigger the opening of a modal window in my Angular application. Below is the code snippet related to this feature: <div class="force-to-the-bottom"> <tag-input [ ...

Is there a way to show uppercase values in Angular's tooltip as capital letters?

Here is my HTML code: <i [class]="item.icon" [pTooltip]="item.item" tooltipPosition="bottom" ></i> The value inside item.item is 'ATTACHMENT' and I am unable to modify it from the ts file. Is there a way ...

Creating a secure API authentication system using Devise

I am currently building a Rails web application that will have a JSON based API for mobile devices. The mobile clients will need to obtain a token using their email and password before they can make subsequent API calls. As a newcomer to Devise, I am sear ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

"Error message when iterating through JSON using jQuery: 'a' is

I've come across similar discussions on this topic, but I haven't found a solution for looping through an array of key-value pairs in the following format: { "quotes": [ { "author": "Author One", "quote": "Quote One" }, { ...

Tips for querying enum data type using GraphQL

I am having trouble querying an enum from GraphQL in my Nest.js with GraphQL project. I keep getting an error message saying: "Enum 'TraitReportType' cannot represent value: 'EMBEDDED'". I have tried using type:EMBEEDED, but it did not ...

The object's value may be 'undefined' after utilizing a switch case to ensure it is not undefined

Before I encountered the error Object is possibly 'undefined'.ts(2532) at testObject["x"], I had used case "x" in testObject. Why did this happen? Should I create my own type guard for it? interface TestObject { a?: number; ...

This error occurred: "Property 'release' cannot be read because it is undefined."

Hello everyone! I'm in need of some assistance. I am trying to test my service tree with a specific structure. Here is an overview of my test: describe(`Service selector`, () => { describe(`getCurrentServiceTree`, () => { it(`should bui ...

When navigating API Pagination, the error message "Unable to iterate through object of type 'NoneType'" may arise

Struggling to develop a code that establishes an API connection, loops through all pages, and generates a data list. The frustrating part is that sometimes the code runs smoothly but other times I encounter the annoying 'NoneType' object is not i ...

Presenting quiz questions using javascript

Currently, I am following the learning path on javascriptissexy.com and facing a challenge with displaying quiz questions in the best way possible. As a beginner student of JavaScript, my question is about how to approach developing the behavior of a quiz ...

Managing numerous subscriptions to private subjects that are revealed by utilizing the asObservable() method

I'm using a familiar approach where an Angular service has a private Subject that provides a public Observable like this: private exampleSubject = new Subject<number>(); example$ = this.exampleSubject.asObservable(); In my particular situation, ...