Retrieve a specific property within a nested JSON object using a single string for reference

When I execute the line

let X = this.appGlobal.GetNavigationLanguage().data;
, it returns JSON data as shown below. https://i.sstatic.net/wdT4e.png

I am trying to extract the string NAV.REPORTS.BMAIL.TITLE.

The translation code (NAV.REPORTS.BMAIL.TITLE) is generated dynamically.

  1. X.NAV.REPORTS.BMAIL.TITLE => works
  2. X['NAV']['REPORTS']['BMAIL']['TITLE']
    => works

However, since the translation code is created dynamically, I need a method like the following:

let transCode = 'NAV.REPORTS.BMAIL.TITLE';
console.log(X[transCode]);

How can I accomplish this task?

Answer №1

sample_data = {
  MENU: {
    ITEMS: {
      FRIES: {
        NAME: "French Fries"
      }
    }
  }
}

let menuCode = 'MENU.ITEMS.FRIES.NAME';
ingredients = menuCode.split('.'); //--> ["MENU","ITEMS","FRIES","NAME"]

output = sample_data
ingredients.forEach(function(ingredient) {
  output = output[ingredient]
})

console.log(output) // --> French Fries

Answer №2

The quicker and darker path would lead you here:

console.log(eval(`X.${transCode}`));

A more ethical approach involves using a recursive function call, limiting the search to specific levels within your string-path (instead of iterating through the entire collection).

const X = {
    NAV: {
        REPORTS: {
            BMAIL: {
                TITLE: 'Test'
            }
        }
    }
}

const transCode = 'NAV.REPORTS.BMAIL.TITLE';

// Quick and dark...
console.log(eval(`X.${transCode}`));  // Test

// More Ethical (but necessitates error handling)...
function getData(input: any, splitPath: string[]) {
    const level = splitPath.pop();

    if (splitPath.length === 0) {
        return input[level];
    } else {
        return getData(input[level], splitPath);
    }
}

const result = getData(X, transCode.split('.').reverse());

console.log(result); // Test

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

What is the solution for the warning "Solid's reactivity is broken when destructuring component props"?

Just starting out with SolidJS and encountering an issue with my UI setup import { render } from "solid-js/web"; import { createSignal, Show } from "solid-js"; import { createStore } from 'solid-js/store'; function Form() { ...

Retrieving Data for Specific Key in JSON Object using BigQuery

I am facing a challenge with a string object stored in a table column, having the following structure: [{"__food": "true"},{"item": "1"},{"toppings": "true"},{"__discount_amount": " ...

Ways to convert all keys to uppercase in an array of objects?

Is there a way to capitalize the first letter of every key in an array of objects? I attempted to achieve this with the code below, but it's not working as expected. Any suggestions or corrections are appreciated. #current code function capitalizeO ...

The error message "React is not defined" is commonly encountered when using React Native Storybook with

While attempting to configure React Native with Storybook, I encountered an issue when importing a .tsx component. The error displayed was: React is not defined ...

A guide on changing JSON into a JavaScript array

I have a JSON data string that needs to be converted into a JavaScript array. Here is the JSON data: [["Claim","1"],["issue","4"]] My desired output: var data = new google.visualization.DataTable(jsonData); data.addColumn('string' , & ...

What is the best way to decode this JSON in Swift? Handling objects that begin with a numerical value

I've managed to successfully parse all the elements in my JSON data except for the "1d" object. Does anyone know how I can go about parsing this particular item? I'm currently using a decodable struct along with JSONDecoder and URLSession. [ { ...

Getting the HTML or JSON response from the WebDriver using Selenium

I'm encountering an issue with the code below that is preventing it from working properly public static String getHTMLResponse(String url){ String body = (String) js.executeScript("$.ajax({url:\""+ url + "\", success:function(result){ re ...

Issue with TypeScript error encountered when attempting to save data locally using React-Redux and LocalStorage

Currently, I am delving into the worlds of React-Redux and TypeScript. Within my small app, I aim to utilize localStorage to store data locally. I attempted to address this based on information from this particular answer, but ran into a TypeScript erro ...

Why isn't my data appearing when using $http.get in AngularJS?

I'm encountering an issue where my bar graph doesn't display data when using $http.get. However, if I eliminate $http.get and directly call the URL, the data shows up perfectly. Any suggestions on what might be causing this problem? AngularJS v ...

Typescript - dealing with a null array reference

Currently, I am working on developing an application using typescript/angular. In this project, I have a service that retrieves JSON data and I want to display these downloaded objects. However, there is a possibility that the number of objects retrieved m ...

Can you explain the significance of tslint's message: "Warning: The 'no-use-before-declare' rule necessitates type information"?

Can someone explain the significance of tslint's "no-use-before-declare" rule warning, which states that it requires type information? I've tried researching online but still don't fully understand its implications. ...

Typescript: Subscribed information mysteriously disappeared

[ Voting to avoid putting everything inside ngOnit because I need to reuse the API response and model array in multiple functions. Need a way to reuse without cluttering up ngOnInit. I could simply call subscribe repeatedly in each function to solve the p ...

What are the most effective strategies for efficiently handling enormous json files?

I have a substantial amount of data stored in JSON format. I am considering the best approach to manage this data, such as loading it into MongoDB or CouchDB on a remote host like Mongolab, using a flat-file JSON database like , parsing the files directl ...

Limit the parameter of a TypeScript method decorator based on the method's type

Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to? I attempted to obtain the method's type that the decorator is applied to using TypedPropertyDescriptor<Method>. However, ...

Steps for integrating Cordova-vk plugin into an Ionic 3 project

I am looking to incorporate the cordova-vk plugin into my app, but I am having trouble connecting it to Typescript. vkSdk is not defined I understand that the plugin is located in the node_modules folder. How can I successfully integrate it into my page ...

Encountering difficulties with a custom Firestore service when attempting to extend it after updating to Angular 9

My custom class that wraps Angular Firestore is designed to be extended and used throughout my application. However, after updating to Angular 9, this setup no longer functions properly. For the complete code snippet, visit . The abstract class wrapper: ...

Is it possible to use ES6 import and require in Typescript 2?

In my Angular2 app, I have a class exported using ES6 modules: //File = init.todos.ts export class Init { load() { ... } } I am importing this class into another component like this: //File = todo.service.ts import { Init } from '. ...

Combining numerous interfaces into a unified interface in Typescript

I'm struggling to comprehend interfaces in Typescript, as I am facing difficulty in getting them to function according to my requirements. interface RequestData { [key: string]: number | string | File; } function makeRequest(data: RequestData) { ...

Using an Angular Promise and Conditional Statement for Authentication Guard

I am trying to implement a guard that determines whether a user can access the login page, but I suspect my approach is flawed due to my use of Promises. Here is the relevant code snippet: canActivate(): boolean | Observable<boolean> | Promise<b ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...