What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3.

In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3.

I want to dynamically push the value of the selected property from each object in demoVars into another array called demoArr.

To achieve this, depending on the value of selectedVar, I need to push the corresponding property value for each object in demoVars into demoArr.

The issue arises when trying to use string interpolation within the push() method to access the value of the selected property. The syntax used results in pushing the string literal instead of the actual value.

I am looking for the correct syntax or approach to accomplish this task effectively.

Answer №1

Try using bracket notation:

for( const item of this.items) {
    this.itemList.push(item[this.selectedItem]);
}

To add an additional layer of security, you can verify if the object possesses the specified property:

for( const item of this.items) {
    if (item.hasOwnProperty(this.selectedItem)) {
        this.itemList.push(item[this.selectedItem]);
    }
}

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

Issue with sending multiple files using FormData and axios in Vuex with Laravel. Server side consistently receiving null. Need help troubleshooting the problem

After trying the solution from my previous question Vuex + Laravel. Why axios sends any values but only not that one, which come's with method's parameter?, I realized that it only works when passing a single argument in axios. I managed to succe ...

In TypeScript, it can be challenging to determine the equality between a value and an enum

I am encountering an issue with my simple code: enum Color { BLUE, RED } class Brush { color: Color constructor(values) { this.color = values.color } } let JSON_RESPONSE = `{"color": "BLUE"}` let brush = new Brush(JSON.parse(JSON ...

Is there a way to use a specific keyboard input to alter the characteristics of shapes on my webpage?

Is there a way to change certain attributes of a shape onscreen when a specific key is pressed by the user? For example, can I make it so that pressing "a" changes the color of the shape? I attempted to modify a mouse rollover event to work with the desir ...

typescript code: transforming object values into keys in typescript

Here is a scenario: const obj1 = { a: 'x', b: 'y', c: 'z', } I am looking to automatically create a type like this: type Type = { x: number, y: number, z: number, } I initially considered the following approach: ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

Issue: Entering data in the input field for each row results in the same value being copied to the qty field

Currently, I have a field where users can enter the quantity for each row. Everything was functioning properly until I decided to add another input field for the pick option. Unfortunately, now it seems that whatever is entered in one field gets duplicated ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

What is the best way to assign the initial value in a dropdown menu populated by a database table?

I'm new to AngularJS and I need help writing a function that can populate a select element with data from a database table. While I am able to fill the select element, I am struggling to set the default value for it. Here is my code: HTML : <div ...

Checking for the status of a checked box when the ::after pseudo-element is added after the box is marked

I need help verifying if a checkbox is checked in my selenium code. After the checkbox is checked, it adds ::after but I'm struggling to confirm the existence of that pseudo element. Can anyone assist me in resolving this issue? I have been unable to ...

Find items where a certain value matches any of the values in another array and return them

I'm seeking assistance with a specific task. I have an object structured as shown below: SOMEKEY: { "key1": val1, "key2": val2 } Additionally, I have an array that contains string values like this: [stringA, stringB, stringC ...

Error message: Invariant Violation: Portal.render() being caused by semantic-ui-react Basic Modal

As part of enhancing an existing React component, I attempted to include a basic modal (link to documentation). Everything was working well without the modal, but once I added it in following the semantic-ui-react guidelines, I encountered a runtime error ...

Unlocking the potential of deeply nested child objects

I have a recursively typed object that I want to retrieve the keys and any child keys of a specific type from. For example, I am looking to extract a union type consisting of: '/another' | '/parent' | '/child' Here is an il ...

What is the best way to save a parsed JSON value to a variable in Express?

I am currently utilizing the body-parser module to parse incoming JSON objects within a POST request. My goal is to extract and store a specific value from the JSON data into a variable for later database insertion. Below is a fragment of the code: var h ...

An error with expanding nodes in the Angular-Kendo UI treeview

I have encountered a potential bug with the Kendo UI treeview in the Angular version that seems to be specific to the k-template option. The bug can be observed on their demo page here: If you expand Item 2, you will notice that the text suddenly changes ...

What techniques can I use to merge alpha channels with compositing in images?

Utilizing an HTML5 Canvas along with the KineticJS(KonvaJS) canvas library, I have successfully incorporated an Image element. My current objective is to erase specific pixels while maintaining a certain level of transparency. The red dot erases pixels at ...

Tips for updating Nodejs' module dependency to a newer version

Currently, my project utilizes the react-cropper library which includes version cropper ^0.10.0. However, I require certain methods from cropper version 0.11.1. To address this issue, I decided to fork the project to my own GitHub repository in order to up ...

With the power of jQuery, easily target and retrieve all label elements within a specified

Currently, I'm working on developing a function that should be executed whenever any of the labels for a particular group of radio buttons are clicked. So, I need a way to reference all the labels in this radio button group. In my search for a soluti ...

At times, JavaScript interacts with Selenium to click on the login button before I have the chance

I have a challenge while attempting to log in to Twitter using Selenium webdriver, here is the code I am working with: const {Builder, By} = require("selenium-webdriver"); (async function example() { let driver = await new Builder().forBrowser(' ...

Angular Automatically Generated Identifier for Event Detection

By using jQuery, I can easily target an ID that starts with "conditionValue" $(document).on('focus', "[id^=conditionValue]", function (event) { // code }); But how can I achieve the same in Angular when looking for an ID starting with somet ...

Converting Epoch 0 to current date with the help of moment.js

Looking for a way to convert an epoch date to a Date object? Here is the code snippet I used: let convertedDate = moment(maintenance.actualEndDate * 1000).format('DD/MMM/YYYY hh:mm'); Keep in mind that if 'maintenance.actualEndDate' h ...