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

Is it time to refresh the sibling element when it's selected, or is there

I have recently started working with react and TypeScript, and I am facing some challenges. My current task involves modifying the functionality to display subscriptions and transactions on separate pages instead of together on the same page. I want to sh ...

Tips for sending a MySQL parameter

Hey there, I need some help with the trigger setup I have: CREATE TRIGGER `update` AFTER UPDATE ON `table 1` FOR EACH ROW INSERT INTO table 2 ( Id, Revision, Purpose, Change ) VALUES ( OLD.Id, OLD.Revision, OLD.Purpose, @purpose_change /* user variable ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...

Could adjusting the 'lib' compiler option to incorporate 'dom' potentially resolve TS error code TS2584?

My preferred development environment is Visual Studio where I write Typescript code. I am facing an issue where I simply want to use the command "document.write" without encountering an error. Unlike my previous PC and VS setup, I am now getting an error ...

Step-by-step guide on permanently updating the text of select options with JavaScript

Here is the code for a select option with different values: <select id="test" onchange="changeContent()"> <option>1</option> <option>2</option> <option>3</option> </select> The javascript function that chan ...

What is the best way to include multiple ng-repeats within a single ng-repeat?

Hey, I'm facing quite a tricky situation with this grid and could use some assistance. I'm trying to figure out how to populate the data using ng-repeat. I've attached an image showcasing the desired layout of the grid and the order in which ...

"Is it possible to access variables declared in the main app.js file from separate route files in Node.js Express 2.5.5 and if so

Recently, I've started using the latest version of Express (2.5.5) which now automatically creates a ./routes directory in addition to ./views and ./public In the routes directory, there is an index.js file that includes: /* * GET home page. */ e ...

Populate a dropdown menu using Javascript

[Code] $.ajax ({ 'method': 'GET', 'source': '/bpv-registratie/periods/show_period_list_by_year.html', 'charge': function () { }, 'finish': function (xmlHttp) { ...

Interact with a webpage element using Selenium

My goal is to extract information from the following page: I want to interact with each blue stats icon on the page (one for every match of the tournament). Below is the code I am using: from selenium import webdriver from selenium.webdriver.common.by im ...

The error message indicated that a Promise<string> was expected, but instead a Promise<string|number> was received

Confusion Over Promise Type Error How did the TypeScript compiler generate the error message displaying Type Promise <string|number> ... in the following scenario? Type 'Promise<string | number>' is not assignable to type 'Prom ...

JavaScript does not function properly with dynamically loaded content

Trying to load the page content using the JQuery load() method. See below for the code snippet: $(window).ready(function() { $('#content').load('views/login.html'); }); .mdl-layout { align-items: center; justify-content: center ...

I am interested in redirecting command line output to a file rather than displaying it in the standard

Is it possible to use child-process and spawn in node.js to execute a command and save the output to a file instead of displaying it on the standard output? test.js const expect = require('chai').expect; const { spawn } = require('child_pr ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

React router updates the URL without affecting the actual display

I am facing an issue in my React project where the URL changes when clicking a link, but the view does not update. I have a separate route and links file, and I can't seem to figure out the problem. Here is my index.js: import React from 'react ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

Implementing specifications throughout the entire nodejs route

In my Nodejs app, I have a RESTful API where I need to check for a user's role before sending a response with data or 404 error. apiRouter.route('/users') .get(function (req, res) { var currentUser = req.decoded; if(curr ...

Angular5 routing causing issues with component rendering

In my application built with Angular 5, this is how my app.module.ts file looks like. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angu ...

Is the $http call for OPTIONS instead of POST?

Hey there, I'm encountering a strange issue while trying to call my backend using the POST method. Remote Address:192.168.58.183:80 Request URL:http://192.168.58.183/ESService/ESService.svc/CreateNewAccount Request Method:OPTIONS Status Code:405 Meth ...

What is the best way to transfer a variable between components in Angular without using the HTML page, directly within the components themselves?

Within the child component, I am working with a string: @Input() helloMessage:string; I am looking to assign a value to this string from another string in the parent component and utilize it within the child component without displaying the value in the h ...