Exploring alternative methods for accessing object values in TypeScript using a string object path without relying on the eval function

If we have an object in JS/typescript structured like this:

var obj = {
  a: {
   b:{
    c:1
   }
  }
}

And a string "b.c" is given, how can we evaluate this using only the variables provided and retrieve the value 1 from the object without relying on techniques like eval as typescript would raise concerns?

Appreciate your insights.

Answer №1

If I understand your question correctly, the keys are known and you can access them using square brackets '[]' like this:

const a = b.c

This is equivalent to:

const a = b['c']

In the second case, you are able to use a variable instead.

When applying this concept to your object, it would appear as follows:

const obj = {
  a: {
    b: {
      c: 1
    }
  }
}

const outerKey = 'a'
const middleKey = 'b'
const innerKey = 'c'

const value = obj[outerKey][middleKey][innerKey]

console.log(value)

I hope this explanation was helpful for you!

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

Developing a RESTful API with Discord.js integrated into Express

Currently, I am faced with the challenge of integrating the Discord.js library into an Express RESTful API. The main issue at hand is how to effectively share the client instance between multiple controllers. The asynchronous initialization process complic ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

What is the best way to transfer the variant property of the material-ui TextField when using a higher-level React component?

I'm encountering difficulties with typing... Essentially, I have a wrapper React component for the @material-ui TextField but I am struggling with getting the typings correct for the variant property. Here's the main problem. Using @material-ui ...

The issue of returning a boolean value in an rxjs function leading to failure

Hey there, I am currently learning about rxjs and I want to create an observable that returns either true or false. This is my attempted code: checkLoggedIn(): Observable<boolean> { // Check with the server if the user is logged in if(this._tok ...

Ways to prompt the user to upload a file and integrate it into my program

Hello everyone, I need some help figuring out how to replace a JSON file with another JSON file that a user uploads. Here is my JavaScript code: var app = angular.module('miApp', []); app.controller('mainController', function ($scope ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...

What is the method for defining a constant data type with a class property data type in typescript?

I've been working on developing a nestjs API and have been using classes to define my entities. For instance, I have created a Customer entity as shown below: export class Customer { id: number; name: string; } Now, while working on my Custom ...

Issue with rendering HTML entities in Material UI when passing as props

Encountered a problem with the radio buttons in Material UI. Currently, Material UI accepts value as a prop for the FormControlLabel component. When passing a string with an HTML entity like below, it gets parsed correctly. <FormControlLabel value="fem ...

A guide to resolving the Angular 11 error of exceeding the maximum call stack size

I am currently working with 2 modules in Angular 11 CustomerModule AccountingModule I have declared certain components as widget components in these modules that are used interchangeably: CustomerModule -> CustomerBlockInfoWidget AccountingModule -&g ...

Tips on accessing files saved in a one-to-many connection using Mongoose

I have multiple Schemas set up for Shops and Products. Each shop can have a variety of products, and I currently have 5 different shops with their own unique product listings. While I am able to save the products and find their corresponding IDs within eac ...

Preventing Angular $rootElement.on('click') from affecting ReactJS anchor tag interactions

Running both AngularJS and ReactJS on the same page has caused an issue for me. Whenever I click on a ReactJS <a> tag, Angular's $rootElement.on('click) event is triggered and the page redirects. I need to perform some functionality in Re ...

Updating a model within an ng-repeat directive from external sources

Within my controller, there is a repeater where each item has its own unique status: <div ng-controller="..."> <div ng-repeat"...">{{status}}</div> </div> Currently, changing the status within the repeater by using status = &apo ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...

Unleash the Power of Animating Your Active Tabs

Is there a way to create animated tabs that slide in when clicked? I've experimented with using transition code but haven't quite achieved the desired effect yet. This is what I currently have: [data-tab-info] { display: non ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

Displaying form after Ajax submission

I have implemented an AJAX code to submit my form, but I am facing an issue where the form disappears after submission. Here is my current code: <script> $('#reg-form').submit(function(e){ e.preventDefault(); // Prevent Default Submissi ...

Navigating through a multistep form in AngularJS using UI Router and arrow keys for seamless movement

Is there a way to navigate to the next or previous form step using arrow keys in AngularJS UI Router? The code provided below is currently allowing navigation with previous and next buttons. .config(function($stateProvider, $urlRouterProvider) { $stat ...

Unsynchronized AJAX POST requests fail to function effectively

I am encountering an issue with an AJAX call that I am using to log in a user. Here is the code: function loginUser() { var xmlhttp; if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest() ...

Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again. However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to ...

Navigating to Protected Mobile Platform

I am experiencing an issue with accessing a .NET website with SSL on my Blackberry device. When I try to view the site, I receive the message "HTTP ERROR 403 FORBIDDEN - You're not authorized to view this page. Please try loading a different page". Th ...