Accessing an object within another object using Typescript

My goal is to access the "rename_fields" object within the main_object collection in order to utilize its field values:

export interface StdMap<T = string> {
    [key: string]: T;
}

export type StdFileBasedPluginHandlerConfiguration<
    SourceType extends StdMap<string | number>
> = {
    type: "std_file";
    data_files: string[];
    exclude_fields: string[];
    value_fields: string[];
    rename_fields: StdMap<StdMap<string>>;
    descriptor: string;
};

export type PluginHandlerConfiguration =
    | StdFileBasedPluginHandlerConfiguration<any>
    | { type: "not_required_configuration" }
    | undefined;

// export type PluginHandlerConfiguration = StdFileBasedPluginHandlerConfiguration<
//     any
// >;


export interface CollectorConfiguration {
    lastUpdate: Date;
    hashFile: string;
    code: string;
    plugin_path?: string;
    plugin_configuration: PluginHandlerConfiguration;
    related_codes?: string[];
    collections: { original: string; names: string[] };
    skipCollectData?: boolean;
    skipFlatGeneration?: boolean;
    extra_grouping_fields: string[];
    has_origins: boolean;
    force?: boolean;
    notify?: boolean;
    origins_that_generate_extra_records?: string[];
}

const main_object: CollectorConfiguration=
{ 
    "code" : "my_code", 
    "lastUpdate" : new Date("2020-01-28T00:00:00.000+0000"), 
    "collections" : {
        "original" : "collection", 
        "names" : [
            "collection_1",
            "collection_2"
        ]
    }, 
    "hashFile" : "ffc0b10ac2e7cd681f5666a474063165f5507212c45abf4ee2f85482ea866985,13c1dd232e13bc6d20ffe6213f38c5152e1f5e7f72366b461602d3cd876ef40f", 
    "extra_grouping_fields" : [
        "type"
    ], 
    "has_origins" : true, 
    "plugin_path" : "file/path_to_plugin", 
    "plugin_configuration" : {
        "type" : "std_file", 
        "data_files" : [
            "../file1.csv", 
            "../file2.csv"
        ], 
        "value_fields" : [
            "value1", 
            "value2"
        ], 
        "descriptor" : "type", 
        "exclude_fields" : [
            "excl1", 
            "excl2"
        ], 
        "rename_fields" : {
            "flat" : {
                "TEST1" : "test1", 
                "TEST2" : "test2", 
                
            }
        }
    }
}

    


Object.keys(main_object).forEach((key: Date | string | StdFileBasedPluginHandlerConfiguration<any> | boolean)=>{
    console.log(`KEY: ${key} - typeof key: ${typeof key}`);
    Object.keys(main_object).forEach((keyConfiguration) => {
        console.log(`DEBUG-->configuration keys: ${keyConfiguration}`);
        if (keyConfiguration === "plugin_configuration") {
            Object.keys(main_object[keyConfiguration]!).forEach(
                (keyPluginConfiguration: any) => {
                    console.log(
                        `DEBUG-->plugin_configuration - ${keyPluginConfiguration} --- END plugin_configuration`
                    );
                    if (keyPluginConfiguration === "rename_fields") {
                        Object.keys(
                            keyConfiguration![keyPluginConfiguration]!
                        ).forEach((keyRenameFields: any) => {
                            console.log(
                                `DEBUG-->rename_fields - ${keyRenameFields} --- END rename_fields`
                            );
                        });
                    }
                }
            );
        }
    });
});


However, I encountered an error message:

test_object_loop.js:50
Object.keys(keyConfiguration[keyPluginConfiguration]).forEach(function (keyRenameFields) { ^
TypeError: Cannot convert undefined or null to object
at Function.keys ()
at test_object_loop.js:50:28
at Array.forEach ()
at test_object_loop.js:47:56
at Array.forEach ()
at test_object_loop.js:44:30
at Array.forEach ()
at Object. (test_object_loop.js:42:26)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)

Is there a way for me to access an object nested inside another object with a specific type?

Answer №1

Instead of using deeply nested loops, consider these steps to retrieve the value of rename_fields:

  1. You can access the value through
    main_object.plugin_configuration.rename_fields
  2. Keep in mind that the type of plugin_configuration is defined as PluginHandlerConfiguration, which means...
    • plugin_configuration could be
      { type: "not_required_configuration" }
      • If this is the case, you won't find a field named rename_fields within it
    • plugin_configuration might be undefined
      • In such instances, you cannot even access its type field

Therefore, a theoretical code snippet would resemble:

// Ensure `plugin_configuration` is defined
if (main_object.plugin_configuration) {
  // Check if `plugin_configuration` includes a field named `rename_fields`
  // by verifying if the `type` field is "std_file"
  if (main_object.plugin_configuration.type === "std_file") {
    // You can now safely retrieve `rename_fields`
    const renameFields = main_object.plugin_configuration.rename_fields
  }
}

Furthermore, the two if conditions can be consolidated into a simpler and more practical code snippet like so:

if (main_object.plugin_configuration && main_object.plugin_configuration.type === "std_file") {
  const renameFields = main_object.plugin_configuration.rename_fields
}

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

No responses received for my post on Node Express - a newbie in the world of Node

My current task involves utilizing an Axios post function to send multipart form data to a Node.js Express endpoint using Multiparty for input field processing. Upon receiving the data, the endpoint saves it in the database. I am looking to utilize the re ...

What could be causing my React Router to display empty pages?

I've been working with the latest version of create-react-app and have been struggling to display the pages within my app. I've tried both functional components and class-based components, but nothing seems to work. I've wrapped the content ...

Notification triggered in GridView editing according to authorization levels

I have a formview displaying data with an option to edit each row. There are different user roles in my system such as Admin, SuperUser, and User. If a non-Admin user tries to edit a row, I want to display a warning message. Currently, the JavaScript funct ...

issue with retrieving data from PHP script via ajax

My attempts to use AJAX to call a PHP script have been unsuccessful. I added an echo alert statement in my deleteitem.php script to ensure it was being called, but no matter what I tried, it never executed. Both the PHP script and the JS script calling it ...

Deciding on the proper character formatting for each individual character within the RICHT TEXT EDITOR

After browsing numerous topics on Stackoverflow, I was able to develop my own compact rich text editor. However, one issue I encountered is that when the mouse cursor hovers over already bold or styled text, it's difficult for me to identify the styl ...

When a dropdown is clicked, it will close any other dropdowns that are currently

Upon clicking on the top menu link "menu item 01", the 3 level drop down opens as expected. Similarly, when you click on "menu item 04", the mega menu expands perfectly. However, I am looking to achieve a functionality where if the user clicks on any othe ...

Encountering a Problem with the onEnter Method in React

Seeking to implement route authentication in my ReactJS app using React Router, I encountered an error when adding the authentication function to the onEnter property of a specific route. Error: Uncaught RangeError - Maximum call stack size exceeded Rout ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...

Retrieving JSON information using dynamic routes in Next.js

I am working with a json file that contains content for various pages categorized under "service". In my nextJS project, I utilize dynamic routes with a file named "[serviceId].tsx" for routing. This setup is functioning correctly. However, I am facing an ...

Error: While working in an Angular project, a TypeError occurs because the property '****' cannot be read when used within a forEach loop

As I attempt to iterate over this.data.members and perform certain actions within the forEach loop on this.addedUsers, I encounter a TypeError: Cannot read property 'addedUsers' of undefined. Interestingly, I can access this.data.members outside ...

The function Sequelize.create() does not exist

My attempts to push my DB with sequelize are not working, even though I have set up this schema for the DB: module.exports = (sequelize, DataTypes) => { const Problems = sequelize.define("Posts", { theme: { type: DataTypes.ST ...

The date selector is failing to accurately reflect changes in the date objects

I've integrated a date-time picker from this source https://github.com/DanielYKPan/date-time-picker to manage 'beginning' and 'end' date objects (refer to selectedMoments in the TypeScript code) for a date selector. However, when I ...

If a 401 response is encountered in Next.js, automatically navigate to the login page

In my project, I utilize Next JS middleware to handle redirection to the login page if there is no token available in middleware.ts: import type { NextRequest, NextResponse } from "next/server"; export function middleware(request: NextRequest, r ...

Having trouble with v-model not updating the data value on a dropdown in Vue.js?

When I set the initial value on the data property, the dropdown option is correctly displayed. However, if I select a different value from the dropdown, the data property does not update accordingly. <select class="form-control" ...

Do not consider file extensions when using child_process fork with node-dev and Typescript

In my Typescript project, I utilize both node-dev and ts-node in my local development environment. To create a subprocess, I make use of the fork method from child_process, as shown here: fork(path.join(__dirname, './worker.ts')); While this se ...

Upon clicking the <p:submenu> element, directly navigate to the first <p:menuitem> element

I am working with a dynamic <p:menubar> as shown below: <p:menubar style="position: relative; height: 30px; visibility: visible;"> <p:submenu label="Category" icon="ui-icon-document" styleClass="mainMenu"> <c:forEach var=" ...

Modify a property of an object using the useState Hook, where the property name is dynamically retrieved from a variable

const [fee, setFee] = useState({newPatient:'',establishedPatient:''}) const field1='newPatient' const field2='establishedPatient' To modify the fee object properties, I am looking to dynamically assign ...

Positioning a toggleable div in relation to its trigger

Struggling to implement Jquery functionality to show/hide a div at the same height as the trigger button. Trying to offset the position of the show/hide div is proving tricky due to varying footnotes positioning. Considering enclosing divs within another d ...

What is the reason behind Selenium altering the href attribute of the element?

Currently, I am utilizing selenium to examine a web element and then retrieve its "href" driver.findElement(getSelectorForButton(name)).getAttribute("href") I'm curious as to why the result I am receiving is ...current url...# instead of just # lik ...

What is the process to retrieve a variable from a Node.js file in an HTML document?

What is the best way to showcase a variable from a node.js route in an HTML File? I have a node.js route structure as follows: router.post("/login", async (req,res) => { try { const formData = req.body const name = formData.name ...