Retrieving the parent object of a nested object within a JSON data structure using TypeScript

Is there a way to programmatically retrieve the parent object from a child object? My goal is to dynamically access the value of a property that belongs to the parent of a child object. For instance, in the given JSON data, I am interested in getting the driver of a specific car:


{
    "driver": [
        {
            "id": 1,
            "name": "Bob", 
            "age": "34",
            "car": [
                {
                    "make": "BMW",
                    "model": "3.20",
                    "colour": "Silver",
                    "mileage": [
                        {
                            "total": "350523",
                            "year": [
                                {
                                    "2011": "3535",
                                    "2012": "7852",
                                    "2013": "8045"
                                }
                            ],
                            "month": [
                                {
                                    "december": "966",
                                    "november": "546",
                                    "october": "7657"
                                }
                             ]
                          }
                       ]
                   }
              ]
         ]
     }

Answer №1

Utilizing for loops:

for(let parent of data.driver) {
   for(let car of parent.car) {
      if(car.make === 'BMW') {
          // modify 'parent' as needed
      }
   }
}

Using filter() or find() (standard javascript):

drivers_who_drive_bwm = data.driver.filter((parent) => {
    // find() will return -1 if no matching car is found with make === 'BWM'
    return parent['car'].find((car) => car.make === 'BWM') !== -1
})

Additionally:

The naming conventions used can be confusing. It would be more intuitive for driver.car to represent a single car, instead of an array of cars in your code. If it consistently contains a single car, consider removing the array. The same goes for .driver, using .drivers could better indicate multiple drivers.

Answer №2

When it comes to selecting a strategy, the key is to iterate through and return based on what you feel most at ease with.

Keep in mind that Typescript is essentially just Javascript, so if you prefer a more Javascript-like "functional programming" approach, utilizing Array map & filter may be best for you.

It's important to recognize that there will likely be application-specific considerations to take into account, such as how to handle instances where the same make/model appears across different drivers.

If functional programming isn't your strong suit, you can opt to create a series of maps and then conduct lookups instead.

In the end, prioritizing your comfort level is crucial in ensuring accuracy in your decision-making process.

Answer №3

When it comes to understanding an Object reference, it's important to remember that it simply represents a memory location without any inherent concept of parents. This means that an object may not necessarily have a parent (although one can be logically assumed), or it could be referenced by multiple other objects (essentially acting as multiple parents).

1> One way to approach this is by assigning a parent reference to each child element programmatically. Keep in mind that parsing a JSON string will not work in this case since it only contains data, not references that are parse-able.

2> Alternatively, you can search for the driver object (or parent object) that contains the child object with the desired value based on your criteria. JavaScript offers array functions like filter and map to help with this task, but ultimately, it involves iterating through and searching for the desired object. In such cases, using a library like Underscore.js can simplify the process.

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

Guidelines on adjusting Angular mat-button attributes using an observable stream

Below is the code snippet I am working with: <button mat-button [disabled]="offline() | async" [textContent]="scanning() ? 'Stop' : 'Start'" (click)="scanning() ? onScanStop() : onScanStart()"> </button> The functi ...

Determine if an array of objects within React JS contains additional objects

I need assistance in displaying the <div className="songs-list-header-col">Album</div> only if the tracks array contains the artist property as an object. In cases where the artist is not an object, I do not want to display the <di ...

Is there a way to access the result variable outside of the lambda function?

My goal is to retrieve data from an external API using Typescript. Below is the function I have written: export class BarChartcomponent implements OnInit{ public chart: any; data: any = []; constructor(private service:PostService) { } ngOnInit( ...

When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected. Here is the structure of my ...

Is it true that SPFx doesn't support JQuery?

Currently, I am in the process of developing a new SharePoint Web Part using SPFx generated by Yeoman. The scaffolding template is working well and I have encountered no issues adding NPMs for JQuery and JQueryUI. As I run GULP SERVE, everything seems to b ...

Threejs file exporter from Blender generating corrupted files

My Blender model seems to be causing issues: After using the threejs exporter in Blender 2.7, the exported json file contains numerous null or 0 values: { "metadata": { "formatVersion" : 3.1, "generatedBy" : "Blender 2.7 Exporter", ...

Troubleshooting compilation problems in Angular2 with nested components

I have created two components in Angular2 using TypeScript: app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles : [` .parent { background : #c7c7c7; ...

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...

What are the steps for utilizing CzmlDataSource within React Resium?

Currently, I'm attempting to showcase the data from a local czml file on a map using React, Typescript, and Resium. Unfortunately, an error keeps popping up stating "This object was destroyed, i.e., destroy() was called." Can someone point out where m ...

Icon for closing Mui Snackbar

I am facing an issue with my notification component that uses the mui snackbar to display alerts. I want to display multiple notifications stacked vertically, but when I try to close one notification using the "Close" icon, it ends up closing both that o ...

The variable 'cache' is not recognized by Angular

Everything runs smoothly on my local Angular app, but once deployed on Heroku using a Go server, I encounter issues with aot being disabled in the Angular build on Chrome and Opera, particularly on mobile devices using Linux and OSX. However, Safari presen ...

Reading JSON files in NodeJS without newline characters

Currently, I am utilizing fs.readFileSync(fileName, 'utf8') to read a JSON file. However, the results contain newline characters, causing the output to appear like this: "{\r\n \"name\":\"Arka\",\r\n ...

Stop the controller from reloading when navigating in Angular2/Ionic2

Initially, I developed my app using tabs. When navigating to a page, the view would load for the first time (fetch data from API and display it), and upon returning to the same page, nothing would reload because the controller did not run again. Recently, ...

Issues with decoding JSON data in PHP

Struggling to assign a JSON Object to a PHP Variable? When attempting to use var_dump, it's showing NULL. Here is the PHP code: <?php $json = utf8_encode(file_get_contents('http://socialclub.rockstargames.com/ajax/stat/1/profile_body/sta1/ ...

Transcompiling TypeScript for Node.js

I'm in the process of developing a Node project using Typescript, and I've configured the target option to es6 in my tsconfig.json file. Although Node version 8 does support the async/await syntax, Typescript automatically converts it to a gener ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

Serializing dates in JSON format in ASP.NET RESTful services

Currently, I am working on developing REST API's that return data in JSON format. ASP.net is responsible for serializing the data, resulting in an output like below: [ { "DueDate": "/Date(1338316200000+0530)/", "User": "XYZ" } ] My goal ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

Attempt to retrieve JSON-formatted data from a repository on Git

As a novice, I am delving into the world of ajax and experimenting with json files. Utilizing JSON formatted data is something I am keen on mastering. However, my request seems to be yielding an empty outcome. An Update: Below is the piece of code I am wor ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...