How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching.

My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which is currently functioning correctly.

currentType = //selection made by user, resulting in either "category1" or "category2"
currentFields = {}
fields = {
           'category1': {
                          propertyInfo {
                                        'label1'
                                        'label2'
                                        'label3'
                                        'label4'
           'category2': {
                          propertyInfo {
                                        'label5'
                                        'label6'
                                        'label7'
                                        'label8'

My aim is for the fields to load when the type is selected. So:

currentFields = field."currentType".propertyInfo

I'm struggling with how to insert the variable into the object path. I keep receiving errors about field not having the property "currentType".

Answer №1

Understanding JavaScript's dynamic nature, the solution can be as simple as this:

currentFields = field[currentType].propertyInfo

If you're not familiar with this concept, it basically means that you can access values in an object like so:

var example = {
  key: "value"
}

The value "value" can be accessed using either example.key or example['key'].

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

What is the best way to access all of a class's properties in JavaScript?

Is there a way to retrieve all the properties of a class using JavaScript? For example, if I have a class like this: .menu { color: black; width: 10px; } How can I extract "color: black; width: 10px;" as a string using JavaScript? Thanks in advance! ...

What are the steps to implement localStorage in Vuejs3?

I'm feeling a bit lost when it comes to localStorage and its usage. I have a component called Statistic.vue which displays a modal at the end. Statistic.vue <template> <p class='modal'>{{numberOfGames}}</p> </template& ...

Ways to attach JQuery UI Sortable widget to html content fetched through Ajax requests?

Here's a straightforward question for you. Take a look at my JavaScript/jQuery code snippet below: $('body .combo-table').sortable({ handle: '.grabber', opacity: 0.9, axis: 'y', start: function (e, ui) { ...

What alternative methods can be utilized to refresh my Angular page without resorting to using location.reload()?

When it comes to this question, there appear to be two possible solutions: $scope.cancel = -> location.reload() or: $scope.cancel = -> $route.reload() The first option works effectively, however, it involves a full GET reques ...

Is it possible for a div with fixed position to still have scrolling functionality

My fixed positioned div (#stoerer) appears to be moving while scrolling, although it is just an optical illusion. Check out this visual explanation: view gif for clarification Below is the code snippet in question: <div id="stoerer"> <button ...

What could be causing the slow loading time of my Shopify App developed using Next.js (React)?

I recently followed a tutorial at However, I am facing severe performance issues with my app. It loads extremely slowly when changing tabs, whether it's running on ngrok, localhost, or deployed on app engine. I'm new to React, Next.js, and Shop ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

"Incorporate keyframes to create a mouseleave event with a distinctive reverse fade

After posing a similar question a few days back, I find myself encountering yet another hurdle in my project. The task at hand is to switch the background image when hovering over a button with a fade-in effect using @keyframes. However, I'm stuck bec ...

Is it possible to reset the text within the text box when the form is being submitted using the load() ajax function?

I am working on implementing a comment feature where the data entered in the form is appended and displayed after submission. Here is my HTML form: <table> <tr><td>Name :</td><td> <input type="text" id="name"/></td&g ...

Steps for integrating Stanford's NLP into a web application

I have successfully developed a project utilizing Stanford's NLP API and models. Now, I am looking to integrate this Java-based project onto the web. After seeing the demo provided by Stanford-NLP, I am curious about the process they use to achieve th ...

Upon encountering an expression, the code anticipated either an assignment or a function call, but instead found an expression, triggering the no

When using the forEach method within a function in JavaScript, I encountered a code compilation failure with the following error: Expected an assignment or function call and instead saw an expression no-unused-expressions. This error occurs for both ins ...

Upon initiating a fresh project with npm create vite@latest and proceeding with npm install, an error message promptly surfaces

semver <7.5.2 Severity: moderate Potential vulnerability in semver due to Regular Expression Denial of Service - https://github.com/advisories/GHSA-c2qf-rxjj-qqgw A fix is available by using the command npm audit fix --force Running this may install [e ...

Manage the application of CSS media queries using JavaScript

Is there a method to control which CSS media query a browser follows using JavaScript? As an example, let's say we have the following CSS: p { color: red; } @media (max-width: 320px) { p { color: blue; } } @media (max-width: 480px) { p { col ...

Considering the move from AngularJS 1.4 to Angular 8 is a significant one, the question arises: should one opt to migrate to 1.5 before upgrading

After conducting extensive research, I am still unsure of the best approach for migrating a large, poorly structured program to Angular 8 (or at least Angular 7). The options of vertical slicing, horizontal slicing, or a complete rewrite all seem dauntin ...

A guide on incorporating oAuth 2.0 into Tizen

Currently, I am in the process of incorporating Google authentication using oAuth 2.0 in Tizen. I am following the guidelines provided here. Despite successfully obtaining the user code as instructed in the link, I keep receiving an invalid request error w ...

Can one customize the background color of a segment in a radar chart using Chart.js?

Could I customize the color of the sectors in my radar chart to resemble this specific image? https://i.stack.imgur.com/U8RAb.png Is it feasible to achieve this using Chart.js? Alternatively, are there other chart libraries that have this capability? It ...

Socketio: Issue: Isolated surrogate U+D83D is not a valid scalar value

I've been experiencing frequent crashes with my node.js server recently, all due to a recurring socket.io error. It seems that the client may be sending invalid UTF strings, causing an error in the utf8.js file. I'm getting frustrated with the co ...

Traverse a collection of nested objects containing arrays as their values

Consider the following object: { "apples": [ "one", "two" ], "oranges": [ "three", "four" ] } If I want to find the value four within this object, how can I do so efficiently? Would a loop work, like the one shown below? for (var ...

Is it feasible to incorporate an external library as a script within a class or functional component in React?

Welcome and thank you for taking the time to read this question! I am currently working on a project where I need to load a TIFF image. After researching, I found a library that can help with this task: https://github.com/seikichi/tiff.js There is also ...

Dynamic jQuery Carousel

Is there a jQuery slider that can adapt to different screen sizes and handle images of varying widths? Appreciate any insights! ...