Create a variable to serve as a key within an Array

Encountering an issue with initializing an array while using the ngx-gauge library to display gauges in my application. One of the attributes is thresholds, which determines three different colors based on the value. For example:

thresholds = {'0' : {color:'red'}, '100' : {color:'green'}, '200': {color:'orange'}};

The problem arises when attempting to replace '0', '100', and '200' with variables. This was my attempted solution:

const level1 = manager.getLevelOne();
const level2 = manager.getLevelTwo();
const level3 = manager.getLevelThree();
thresholds ={ level1 : {color:'red'}, level2:{color:'green'}, level3:{color:'orange'}};

However, when printing out thresholds with console.log, it displays level1, 2, and 3 as aliases rather than their actual values.

Answer №1

One reason why using

thresholds= { level1: {color: 'red'}}
doesn't function as expected is because it's essentially the same as
thresholds= { "level1": color: 'red'}}
(with quotes). In JavaScript, these two versions are interchangeable as long as level1 follows the rules for a legal identifier, but using the second version clarifies the syntax better.

const level1 = "0";
const level2 = "100";
const level3 = "200";
thresholds = {
  [level1]: {
    color: 'red'
  },
  [level2]: {
    color: 'green'
  },
  [level3]: {
    color: 'orange'
  }
};
console.log(thresholds);

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

Guide to managing MUI's theme typography font weight choices with TypeScript

I am interested in learning how to incorporate a new font weight into my theme, for example, fontWeightSemiBold, and disable the existing fontWeightLight and fontWeightMedium. I believe this can be achieved through module augmentation. For reference, there ...

Developing Components in Angular 2.0 with the assistance of ui-router

I am currently in the process of transitioning an Angular 1.x application to utilize Angular 1.5 components, a new feature that will be relevant for Angular 2.0. As far as I can tell, I need to create a Root Component that will serve as the main bootstrap ...

The angular 2 router is failing to navigate properly when using the history forward/backward button

The history push state feature is not working properly with the Angular 2 router in both Chrome and Firefox. The forward button never works, and the backward button only works for 2 steps before the UI stops responding to it. Here is the code I am using: ...

When you click on the mat-tab label, it will act as a link and directly open the

I am facing an issue where I have 4 mat-tabs and I want to add one more tab. This additional tab will act as a label that, when clicked, opens a provided link. I have tried the following code but it is not working: <mat-tab label="Statistik ...

Passing an array to the Router using queryParams in Angular 2

Is there a method to generate a similar URL structure in Angular 2? http://example.com/the-route?param[]=value1&param[]=value2&param[]=value3 I've been attempting to achieve this using queryParams with the Router. However, since queryParams ...

Tips for organizing a multi-dimensional array based on various column indexes

I am looking to organize a multidimensional array by multiple column index. Take, for instance, the test data provided below: var source = [ ["Jack","A","B1", 4], ["AVicky","M", "B2", 2], [ ...

Transform AngularJS service into Angular service

I am looking for guidance on how to migrate from AngularJS to Angular. I have a component called ForgotPassword and I am unsure of the correct method to send an http.post request to my C# controller. function (window, angular) { "use strict"; angular.m ...

Passing properties to a component from Material UI Tab

I have been attempting to combine react-router with Material-UI V1 Tabs, following guidance from this GitHub issue and this Stack Overflow post, but the solution provided is leading to errors for me. As far as I understand, this is how it should be implem ...

Typescript allows for the use of either a single string or an array

Here is a definition that I am working with: interface Field { question: string, answer: string | string[], } However, when I try to implement the following code snippet: if (typeof answer === 'string') { const notEmpty = answer.trim().len ...

Access the CSV file using Office365 Excel via a scripting tool

Objective I want to open a CSV file using Office365's Excel without actually saving the file on the client's machine. Challenge The issue with saving raw data on the client's machine is that it leads to clutter with old Excel files accumu ...

Issue with Bootstrap 4.3.1 - unable to turn off validation icons

I have come across answers on Stack Overflow about disabling Bootstrap validation icons. There are two suggested solutions: $enable-validation-icons: false; (this is also recommended in Bootstrap's theming documentation) Utilize SCSS/CSS to eliminat ...

Why does JavaScript not wait for the completion of forEach and instead executes the next line immediately?

While creating my api in nodejs and attempting to push the mongoose return count to a newly created array, it does not wait for the forEach loop to finish before executing json.res() and returning a null response. However, when I use setTimeout(), the re ...

What is the best way to enforce input requirements in Typescript?

I am currently facing an issue with two required inputs that need to be filled in order to enable the "Add" button functionality. I have considered using *ngIf to control the visibility of the button based on input values, but it seems to not be working. ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

Discover the steps to create a virtual scroll dropdown menu with Kendo in Angular

I'm dealing with a large data set obtained from an API. Instead of displaying all the data in the dropdown initially, I'd like to fetch the results from the server API as the user scrolls down through the dropdown menu. Could someone please prov ...

Is there a way to change a .pptx document into a base64 string?

Currently, I am working on a project that involves creating an addin for Office. The challenge I am facing is opening other pptx files from within the addin. After some research, I discovered that I need to use base64 for the PowerPoint.createPresentation( ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Angular indicates that there is a problem with the property 'x' as it is not found in the type 'y[]'

I am trying to display the details of users using the *ngFor directive, but encountered an error earlier. Here is the code snippet: this.users=[ // first user { firstName: 'John', lastName: 'Doe', c ...

Priority of Search Results in Ionic Search Bar

I have an array of items that I'll refer to as fruitArray. fruitArray = ['Orange', 'Banana', 'Pear', 'Tomato', 'Grape', 'Apple', 'Cherries', 'Cranberries', 'Raspberr ...

Go through each subscriber

I'm struggling to grasp the concept of the observer/subscriber model and how to iterate through the returned data. For example, I have a cocktail component that fetches an array of cocktail objects. The key part of cocktail.service.ts: constructor( ...