Adaptively linking to the property of a deeply nested object

Attempting to bind to a property of a nested object using [(ngModel)], but facing the challenge that the path to the property is dynamically set.

Consider the following three classes:

class A {
 p1: C
 constructor() {
  p1 = new C("A")
 }
}
class B {
 p2: C
 constructor() {
  p2 = new C("B")
 }
}
class C {
 constructor(public id: string){}
}

reusable.component.html looks like this:

<input [(ngModel)]="data[propName]">

reusable.component.ts looks like this:

@Component({
  selector: "app-reusable[data][nestedProperty]",
  templateUrl: "./reusable.component.html"
})
export class ReusableComponent<T> {
 @Input()
 nestedProperty!: string
 @Input()
 data!: T
}

and app.component.html as follows:

<app-reusable [data]="d1" [nestedProperty]="s1"></app-reusable>
<app-reusable [data]="d2" [nestedProperty]="s2"></app-reusable>

and app.component.ts like so:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
d1 = new A()
d2 = new B()
s1 = "p1.id";
s2 = "p2.id";
}

The original idea was for d1.p1 to have the same value as d1["p1"], but it was discovered that d1["p1.id"] does not yield the same result as d1.p1.id.

Is there any workaround to retrieve a nested object value solely using a string path to the nested object?

One solution involved creating the property d1["p1.id"] within the constructor and assigning it the d1.p1.id value like this:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
d1 = new A()
d2 = new B()
s1 = "p1.id";
s2 = "p2.id";

 constructor() {
  this.d1[s1] = this.d1.p1.id
  this.d2[s2] = this.d2.p2.id
 }
}

Answer №1

To retrieve the value of a property using its path, you can utilize the eval function to evaluate the expression:

The eval() function interprets JavaScript code that is represented as a string.

If you have an object defined like this:

var myObject = {
   innerObject: {
      nestedProperty: 'The value'
   }
};

You can access the value 'The value' by executing:

var nestedValue = eval("myObject.innerObject.nestedProperty");
// The variable nestedValue now holds the value 'The value'

It's important to note that using eval can pose security risks as it will run any string as code. A safer alternative in this scenario is to use the Function method. More information on why eval should be avoided can be found here.

function extractProperty(path) {
   return Function('"use strict";return (' + path + ')')();
}

You can then use this approach for the previous example:

var nestedValue = extractProperty("myObject.innerObject.nestedProperty");

This code snippet follows standard JavaScript practices, but it can be adjusted to suit your TypeScript requirements.

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

"An error has occurred: ENOENT - The specified file or directory does not exist, cannot create directory" on the live website

I am facing an issue on my website where I need to create a folder and save some files in it. While the code works perfectly fine locally, once deployed on render, I encounter the following error: Error: ENOENT: no such file or directory, mkdir '/opt/ ...

Effortless gliding towards the left

I am looking to incorporate buttons for smooth horizontal scrolling within my container. Currently, the functionality is in place but I would like to enhance its smoothness. How can I improve the scrolling experience? Should I consider using a different p ...

Erroneous deletion issue in React list causing removal of incorrect item

While working on creating a todo list in React, I faced an issue when trying to implement a delete function. The problem arose when attempting to delete an item - instead of removing the selected item, React ended up deleting everything except that specif ...

Problems encountered while trying to install the angular2-meteor package using npm

Attempting to kick off a fresh angular2-meteor project with the command: npm install angular2-meteor --save Encountering a slew of red errors (shown below) and I'm puzzled by their significance. Already executed npm install npm -g and npm ...

What is the method for initiating a radial gradient from the middle of the pie chart?

In my pie chart with grid lines, I have successfully implemented a radial gradient. However, the issue is that there is a separate gradient for each pie slice. What I really want is a single gradient originating from the center of the entire pie chart. I ...

Creating a stylish zebra pattern using JCrop on the cropping window

Lately, while using jquery jcrop, I've noticed a peculiar design appearing on the cropping window. The details of this pattern are unclear to me. What could be the reason behind the zebra-like pattern visible on the cropping window? Is there any spec ...

Execute a bash script from a local URL using fetch

I'm curious about converting a curl command into a bash script with input variables using fetch. It works perfectly in the console: curl -s http://localhost:3001/ident.sh | bash /dev/stdin x627306090abab3a6e1400e9345bc60c78a8bef57 2 10194897676576 ...

What is the best way to reference an Angular constant within a Gulp configuration file?

Is it possible to retrieve an Angular constant within a Gulp file? For example: angular.module('app').constant('env', { url: 'http://localhost:1337/' }); What is the method for accessing this constant inside a function ...

What is the best way to toggle the visibility of fields on a modal in a Ruby on Rails

I am working on an application that utilizes Rails 4.1 and Ruby 2.1.2. The show.html.erb view for the Assignment Model in this application is as follows: <h1><%= "#{'Source URL'}"%> <div class="source-url"><%= @assignment.so ...

The character replacement function does not seem to be functioning properly in DialogFlow following the use of

Is there a way to replace commas with colons in the 'setTime' result? I attempted to create another variable and then use the replace() method, but it resulted in an error message stating "Webhook call failed. Error: 500 Internal Server Error". ...

Tips for adjusting the size of grid tiles according to the dimensions of the window within a specific range

I am currently exploring how to replicate the effect found on this webpage: When the window size is adjusted, javascript dynamically resizes the grid tiles between 200 and 240px based on the optimal fit for the screen. Is there a ready-made JavaScript/jQ ...

After refreshing the page in Next JS, there is a delay in loading the Swiper Js styles. The Swiper slides appear stretched while waiting for Next JS to load the styles. Any suggestions

Having an issue with my Next 14.0.3 app and tailwind CSS. I recently installed swiper JS version 11.0.5 using npm. The problem arises when I reload the page, it takes about 1 or 2 seconds for the swiper styles to load. During this time, the swiper slides s ...

What happens when two style() functions are passed into the query() function for Angular Animations?

As someone who is relatively new to angular animations, I have reviewed the angular.io animation documentation multiple times in order to grasp how everything functions. While I believe I have a decent understanding, there are certain scenarios that the do ...

Changing Images with Jquery on Click Event

This section of the HTML document contains an image link that is designed to switch between two images when clicked. The images in question are timeline-hand and hand-clicked. Clicking on the image should change it from one to the other and vice versa. Ho ...

What causes the UnhandledPromiseRejectionWarning while attempting to launch a browser with chromedriver?

I'm having trouble trying to launch a chrome browser and navigate to google.com using selenium chromedriver with node.js. Despite no version mismatch between the chromedriver and the browser, I encounter the following error message and the browser fai ...

Accessing a JSON file in JavaScript

My website has a script that populates dropdown menus and is currently running from a custom.js file. While it works well, there is one aspect of it that I am not entirely satisfied with. The script involves embedding the various levels of menu, which am ...

Union types can be used to constrain generic type parameters in Typescript

I'm working on a function uniqueIds(first: any[], second: any[]): number[] { let prop = first[0] instanceof Owner ? "OwnerId" : "BankId"; return _.unique( _.map( first, o => ...

Why is this <div> element refusing to budge according to my jQuery commands?

Currently embarking on a jQuery coding challenge where I am attempting to maneuver a circle around the page in a square pattern. Numerous methods have been tested with no success thus far. While I would like to showcase my various attempts, it would prove ...

CSS classes designed to mimic JavaScript object attribute-value pairs

I stumbled upon some interesting css class-value combinations within HTML tags. It seems like a specific JavaScript code is interpreting this, but it's something I haven't encountered before. I came across this on www.woothemes.com/flexslider/ (y ...

The element in Selenium's net.serenity.bdd.core.exceptions.SerenityManagedException has encountered a timeout issue

I'm having difficulty choosing a radio button on this particular form: <form _ngcontent-c4="" novalidate="" class="ng-untouched ng-pristine ng-invalid"> <div _ngcontent-c4="" class="text-center"> <div _ngcontent-c4="" class=" ...