Tips for transforming a string into a variable within an Angular framework

I'm working with a JSON object retrieved from an API

let arr = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}]

Now I need to create a function that can be called

public testFunc(data, prop){
  console.log('Desired property value : ', data[1][prop])
}

If I call

this.testFunc(arr,'name');

The expected output would be

Desired property value : qwe

Could anyone provide me with guidance on how to achieve this?

Thanks in advance

Answer №1

Typically, there are two methods to access a property of an object:

  • someObject.prop
  • someObject['prop']

When accessing a property of an object using a variable, bracket notation is utilized like so: obj[<variable>].

Here's an example demonstrating this concept:

let a = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}];

//Includes the option to specify an index
const printPropValue = (data, index, variable) => data[index][variable];

console.log(printPropValue(a, 1, 'name'));
console.log(printPropValue(a, 0, 'age'));
//console.log(printPropValue(a, 4, 'name')); --> Will result in an error

It's important to address edge cases when using this approach, such as handling situations where the object at that particular index might be null or undefined. Various methods exist to handle these scenarios,

let a = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}];

//Includes the option to pass index as well
const printPropValue = (data, index, variable) => data[index]?.[variable];

console.log(printPropValue(a, 1, 'name'));
console.log(printPropValue(a, 0, 'age'));
console.log(printPropValue(a, 4, 'name'));

  • Another approach involves using || (OR operator)

let a = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}];

//Includes the option to pass index as well
const printPropValue = (data, index, variable) => (data[index] || {})[variable];

console.log(printPropValue(a, 1, 'name'));
console.log(printPropValue(a, 0, 'age'));
console.log(printPropValue(a, 4, 'name'));

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

Creating a TypeScript mixin with a partial class is a useful technique that allows you to

I am attempting to have class A inherit properties from class B without using the extends keyword. To achieve this, I am utilizing a mixin in the following manner: class A{ someProp: String someMethod(){} } class B implements classA{ someProp: String ...

Encountering a ReactJs and TypeScript error: "menuItems.map is not a function, issue with map method"

Greetings! I am currently working on implementing the logic of using useState and mapping an array to show only one dropdown item at a time. Below is my array structure with tags (menu name, links (to router), icon (menu icon), and if there are dropdown i ...

Managing responses in Angular 6 - dealing with error code 429

Is there a way to handle a 429 error response on the HttpClient in Angular 6? The code snippet provided successfully captures a 401 error, but when it comes to a 429 error, it triggers an unknown error message. Error/Edit: The issue arises during the pre ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

Issues with Next.js and Framer Motion

My component is throwing an error related to framer-motion. What could be causing this issue? Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function This error occurred during page generation. Any console logs will be ...

Changing Angular 6 form groups into query parameters for GET requests

Question: I need to retrieve information from a Web API using a GET request, with the parameters being in filter form. The request is straightforward: filterEvents() { this.http .get(environment.apiUrl + 'events/GetFilteredAxmCardsId' ...

What is the best way to implement material theme colors into my Angular2 CSS?

Suppose I want to utilize the mat-primary color as a background for a div using a CSS/SASS class, how should I reference it? My initial thought was: @import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; .my-class{ background-colo ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...

The issue of data being duplicated when clicking on react-cookie-consent

Currently, I am utilizing the npm package https://www.npmjs.com/package/react-cookie-consent to implement a cookies consent feature in my react TypeScript application. However, I have encountered two issues with this package. Firstly, upon clicking the acc ...

Table with dynamic rows containing different number of sub-sections

Looking to utilize the mat-table directives, such as *matRowDef and multiTemplateDataRows in order to construct a table with dynamic sub-rows for each main row. To illustrate, consider the following interface: interface ReportCard { student: string; r ...

What is the best way to flatten a 2D array using TypeScript?

If I have an array structured like this: [0]: ["id_1"]: prop1: "abc" prop2: "def" ["id_2"]: prop1: "ghi" prop2: "jkl" [1]: ["id_3"]: prop1: "mno" prop2: "pqr" ["id_4"]: prop1: "stu" ...

It seems that Ionic 2 does not support the registration of custom HTML tags

Encountering a problem with Ionic 2 and custom components. Developed a component to show in a list, serving as the list item. However, my app crashes when attempting to use the custom HTML tag. The stack trace is provided below. Uncertain about the issue. ...

Exploring Facebook Graph API response with Angular 2 Mapping

I am using HTTP calls to access the Graph API in order to retrieve posts from a Facebook page. Here is the code snippet that fetches an array of posts: let url = 'https://graph.facebook.com/15087023444/posts?fields=likes.limit(0).summary(true),comme ...

I encounter an issue when trying to declare an enum in TypeScript

At line 26 in my typescript file, the code snippet below shows an enum definition: export enum ItemType { Case = 'Case', Study = 'Study', Project = 'Project', Item = 'Item', } I am currently using Visual Stu ...

Navigating the interface types between Angular, Firebase, and Typescript can be tricky, especially when working with the `firebase.firestore.FieldValue`

I am working on an interface that utilizes Firestore timestamps for date settings. export interface Album{ album_name: string, album_date: firebase.firestore.FieldValue; } Adding a new item functions perfectly: this.album ...

AG Grid is displaying improperly within Angular

I am facing an issue with using ag-grid in my project. The output is not as expected and I am unsure of what the problem might be. Here is a snippet of my HTML code: <p>user-access works!</p> <ag-grid-angular style="width: 500px; height: 50 ...

Having trouble with routerLink in your custom library while using Angular 4?

In my Angular 4 project, I have developed a custom sidebar library and integrated it into the main project. My current issue is that I want to provide the option for users to "open in new tab/window" from the browser's context menu without having the ...

Is it necessary for me to develop an Angular library in order to release a basic TypeScript class that makes use of Angular components?

In one of my Angular projects, I have a Typescript class called APIResponse that I want to convert into an NPM package for use in other projects. This class is not specific to Angular like a Service or Component. After doing some research on creating non-A ...

The router's handler function sends back a collection of objects, but for some reason, the client is not receiving them in JSON format even though the response

I am currently developing an Express.js project using Typescript. In my project, I have defined an enum and an interface as follows: export enum ProductCategory { ELECTRONICS = 'electronics', CLOTHING = 'clothing', TOYS = & ...

Error Type: Jest: A transform is required to have a `process` function in order for it to

Encountering an error while running 'npm test': FAIL __tests__/unit/domain/services/demo-service.ts ● Test suite failed to run TypeError: Jest: a transform must export a `process` function. at ScriptTransformer._getTransformer ( ...