tips for extracting nested JSON data using TypeScript

I need assistance in extracting the state parameter values for each id - 2434,78657 using typescript. Due to the nested JSON structure, I am encountering difficulties in fetching these values.

JSON Request:

                        { 
                           "2434":[ 
                              { 
                                 "eventId":"90989",
                                 "eventTime":"2019-12-11T11:20:53+04:00",
                                 "eventType":"yyyy",
                                 "event":{ 
                                    "ServiceOrder":{  
                                        "priority":"1",
                                       "state":"InProgress"}
                                 }
                              },
                              { 
                                 "eventId":"6576",
                                 "eventTime":"2019-12-11T11:20:53+04:00",
                                 "eventType":"yyyy",
                                 "event":{ 
                                    "ServiceOrder":{ 
                                       "priority":"1",
                                       "state":"InProgress"
                                    }
                                 }
                              },
                              { 
                                 "eventId":"6576",
                                 "eventTime":"2019-12-11T11:20:53+04:00",
                                 "eventType":"yyyy",
                                 "event":{ 
                                    "ServiceOrder":{ 
                                       "priority":"1",
                                       "state":"Pending"
                                    }
                                 }
                              }
                           ],
                           "78657":[ 
                              { 
                                 "eventId":"6576",
                                 "eventTime":"2019-12-11T11:20:53+04:00",
                                 "eventType":"yyyy",
                                 "event":{ 
                                    "ServiceOrder":{ 
                                       "priority":"1",
                                       "state":"Pending"
                                    }
                                 }
                              },
                              { 
                                 "eventId":"6576",
                                 "eventTime":"2019-12-11T11:20:53+04:00",
                                 "eventType":"yyyy",
                                 "event":{ 
                                    "ServiceOrder":{ 
                                       "priority":"1",
                                       "state":"Completed"
                                    }
                                 }
                              },
                              { 
                                 "eventId":"6576",
                                 "eventTime":"2019-12-11T11:20:53+04:00",
                                 "eventType":"yyyy",
                                 "event":{ 
                                    "ServiceOrder":{ 
                                       "priority":"1",
                                       "state":"Failed"
                                    }
                                 }
                              }
                           ]
                        }

Desired Output:

To illustrate, an array containing all state parameter values should be returned for id 2434.

[InProgress, InProgress, Pending]

Answer №1

Here is the answer you need:

This solution is designed to be dynamic, allowing for any number of keys in your Object. It retrieves the state value of all keys through nested looping.

Below is the code that performs this magic:

let object = {};
for (let key of Object.keys(test)) { 
    for (let value of test[key]) { 
        object[key] = object[key] || []
        object[key].push(value['event']['ServiceOrder']['state'])
     } 
 } 

Execute the code snippet below:

 // Code snippet goes here 

Please run the above snippet to see the result.

The output will be:

{ "2434": ["InProgress", "InProgress", "Pending"], "78657": ["Pending", "Completed", "Failed"] }

Working DEMO available here

Answer №2

This solution should assist you. To start, decode the JSON data.

$result =  json_decode($row[1]);
echo $result->{'2434'}[0]->event->ServiceOrder->{'**state**'};

See the results below.

answer: InProgress

Answer №3

Take a look at this code snippet. You just need to provide a specific ID (e.g., 2434) in order to retrieve the status associated with it. Simply input the ID and receive the status as an array.


function getStatusFromId(id: number){
  return new Promise((resolve, reject) => {
    let idObject = NotificationData[id];
    let arrayOfStatus = new Array();
    idObject.forEach((data) => {
      arrayOfStatus.push(data.event.ServiceOrder["**state**"])
    })
    resolve(arrayOfStatus);
  })
}


getStatusFromId(id)
.then((data) => {
  console.log(data)
});
let NotificationData = { 
                       "2434":[ 
                          { 
                             "eventId":"90989",
                             "eventTime":"2019-12-11T11:20:53+04:00",
                             "eventType":"yyyy",
                             "event":{ 
                                "ServiceOrder":{  
                                    "priority":"1",
                                   "**state**":"InProgress"}
                             }
                          },
                          { 
                             "eventId":"6576",
                             "eventTime":"2019-12-11T11:20:53+04:00",
                             "eventType":"yyyy",
                             "event":{ 
                                "ServiceOrder":{ 
                                   "priority":"1",
                                   "**state**":"InProgress"
                                }
                             }
                          },
                          { 
                             "eventId":"6576",
                             "eventTime":"2019-12-11T11:20:53+04:00",
                             "eventType":"yyyy",
                             "event":{ 
                                "ServiceOrder":{ 
                                   "priority":"1",
                                   "**state**":"Pending"
                                }
                             }
                          }
                       ],
                       "78657":[ 
                          { 
                             "eventId":"6576",
                             "eventTime":"2019-12-11T11:20:53+04:00",
                             "eventType":"yyyy",
                             "event":{ 
                                "ServiceOrder":{ 
                                   "priority":"1",
                                   "**state**":"Pending"
                                }
                             }
                          },
                          { 
                             "eventId":"6576",
                             "eventTime":"2019-12-11T11:20:53+04:00",
                             "eventType":"yyyy",
                             "event":{ 
                                "ServiceOrder":{ 
                                   "priority":"1",
                                   "**state**":"Completed"
                                }
                             }
                          },
                          { 
                             "eventId":"6576",
                             "eventTime":"2019-12-11T11:20:53+04:00",
                             "eventType":"yyyy",
                             "event":{ 
                                "ServiceOrder":{ 
                                   "priority":"1",
                                   "**state**":"Failed"
                                }
                             }
                          }
                       ]
                    };


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

Issue encountered while conducting tests with Jest and React Testing Library on a React component containing an SVG: the type is not recognized in React.jsx

In my Next.js 12.1.4 project, I am using Typescript, React Testing Library, and SVGR for importing icons like this: import ChevronLeftIcon from './chevron-left.svg' The issue arises when running a test on a component that includes an SVG import, ...

How to send information from parent component to child in Angular 15

Currently, I am in the process of learning Angular, so please bear with me if my terminology is not entirely accurate. Below, you will find a complete output at the end of this post. At present, I have code that successfully triggers a hard-coded modal. H ...

Transform a JSON-style text into a PHP array

Having some data in JSON format saved as a string in a text area may seem like JSON, but technically it's not. How can I convert this string into an array using PHP? Let's take the example of latitude and longitude coordinates needed for a Google ...

Implementing conditions in Angular2 router

Here are my current routes: const appRoutes: Routes = [ { path: 'alert/:id', component: AlertDetailComponent }, { path: 'alerts', component: AlertsComponent }, { path: 'dashboard', component: EriskDashboardComponent }, { pa ...

I am encountering issues with JSON validation in Swift for the data retrieved from my web api, and I am puzzled about

Below is the example of Swift code: if JSONSerialization.isValidJSONObject(JSONData) { print(":Valid json") } else { let JSONstring = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) print(JSONstring) } This piece of code trigge ...

Using Spring to consume a REST service with dynamic JSON fields

After receiving a JSON request from JavaScript to update a MongoDB collection, I found that part of the JSON was mapped to my Java class (Person), but the inner JSON had dynamic field names. I decided to map the dynamic fields to a JsonObject instead, but ...

Can anyone provide guidance on how to navigate through a JSON array within a JSON response using Flutter? I'm relatively inexperienced in Flutter and

I'm working on parsing a JSON response into a model and nested model class in Flutter. Can someone help me understand how to read this JSON structure effectively? I really appreciate any assistance as I am new to handling JSON responses in model class ...

How can I insert an external object into a list and append it to every object within the list?

My current issue involves iterating through an array and appending an object that is outside the list to each object inside the list. Unfortunately, I am encountering difficulties in achieving this. The 'offerings' array contains multiple objects ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Enlist a variety of Angular2 components to a Service for enhanced functionality

My goal is to establish communication between two Components using a Service that is triggered when another Component reacts to a DOM event. To achieve this, I intend to leverage the power of RxJS Subject Observable, or potentially its subclasses like Beh ...

Contrasts between the text/plain format and the application/json type

I'm pondering the distinction between text/plain and application/json. Which one is the preferred choice and how should they be properly used? Recently, I made a POST request to API Routes in NextJS without specifying headers. The Content-Type of the ...

Typeorm retrieve values of fields depending on their datatype

I have a TypeORM entity called SuperResource @Entity() export class SuperResource extends BaseEntity { @PrimaryGeneratedColumn() id: number; @OneToOne(() => Resource, {cascade: true, eager: true}) @JoinColumn() resource: Resource @Column({ ...

The Angular 2 component is experiencing difficulty in fetching data from the service

My current predicament is fairly straightforward - I am attempting to fetch data from an Angular 2 service, but the target array always ends up empty. Despite seeing that the API call returns data with a status of 200 and no errors are displayed in the con ...

How to capture JSON data using PHP

My dilemma involves a specific URL format, which is detailed below: localhost/handikap/insert/index.php?json={"id":123456} My goal is to extract the JSON response from this URL. I have attempted to achieve this using the following code: $data = json_dec ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

Creating JSON for a Variety of Outcomes in Azure Mobile Services

Need help with Custom API in Azure Mobile Services to retrieve rows from a table and return them in JSON format: exports.post = function (request, response) { var tables = request.service.tables; var accountSensor = tables.getTable('AccountSe ...

What is the best way to integrate Google Analytics into a Next.js application without the need for an _app.js or _document.js file?

I'm encountering some challenges while trying to incorporate Google Analytics into my Next.js application. One issue I'm facing is the absence of an _app.js or _document.js file in the project structure. Additionally, I notice that when I include ...

Tips for incorporating an icon beneath the title of an angular echart

How can I add an icon below the Echart title? I have attempted the following but have been unsuccessful in rendering the icon. https://i.sstatic.net/PUURP.png The code in my component.ts file is as follows: constructor(private sanitizer: DomSanitizer) { ...

Deciphering JSON data in Ext JS

function symbol_handler(){ fp.getForm().submit({ url:'/index.php/ajax/test_function', success:function(resp){ //how can I access the attributes of the JSON object? } }); edit: here is the PHP controller, in case it is ...

When using Angular to send a request body containing IFormFile to an ASP.NET Core Web API, the properties are unexpectedly null

I am facing an issue with sending a request body as an object from Angular to ASP.NET Core Web API. All the properties are coming up as null except for ID. Here is the structure of my Web API: public class Book { public int BookID { get; set; } pu ...