retrieve an object with enum keys that are indexed

I am faced with a situation where I have a collection of interdependent elements, each identified by a unique code (enumeration). My goal is to retrieve the list of elements that depend on a specific element, and then be able to reference them using myElements[anElementCode]:

enum Code {
  A = 'A',
  B = 'B',
  C = 'C',
  D = 'D',
}

function main() {
  let myElements = [
    { Code.C: [Code.A, Code.B] },
    { Code.D: [Code.B] }
  ]
  console.log(`The Elements that depend on C are: ${myElements[Code.C]}`); 
}

I want to be able to access the list [Code.A, Code.B] using myElements[Code.C]

Although this code doesn't currently work as intended, I am curious if there is a workaround to achieve the desired functionality?

Answer №1

By setting myElements as an array, you are actually in need of a dictionary with square brackets for dynamically defining keys. Here's the corrected version:

function main() {
    let myElements = {
        [Code.C]: [Code.A, Code.B],
        [Code.D]: [Code.B]
    };
    console.log(`The Elements that depend on C are: ${myElements[Code.C]}`); 
}

Try it out here

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 altering JSON using Javascript

https://github.com/smelukov/loftschool-example i am currently working on my project in this environment. I have created a friends.json file in the main folder. friends.json { "name": "John", "lastName": & ...

How can I retrieve query parameters in the Server app directory of Next.js 13 using a function?

I am looking to retrieve a query token from localhost/get/point?token=hello. import { NextResponse } from 'next/server' import base64url from 'base64url' type Params = { token: string } export async function GET(req: Request, contex ...

What is causing the net::ERR_CONNECTION_RESET in Node JS and ExpressJS?

Our application, built on ExpressJS and NodeJS, is hosted on a Linode server and served at port 3000. Although the app has been functioning well for a year, we have recently encountered consistent connection errors. The errors vary, but they are mostly re ...

Loading state with suggestions from autocomplete feature on React

In my current project, I have a component that consists of input fields and a button. The button is set to be disabled until the correct values are entered in the input fields. Everything works as expected, but there's an issue with Chrome auto-fillin ...

Exploring the gridview with JQuery to iterate through and verify if any checkboxes have been selected

I am currently working on a jQuery-based application. In this application, I have an ASP.net GridView that contains checkboxes in each row. My goal is to determine whether any of the checkboxes are checked or not. Below is the code snippet where I loop thr ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

An approach to looping through arrays within an object in JavaScript

I have a JSON structure that consists of an array containing arrays, each holding dictionary elements. This data is retrieved from a function-based view. I am looking to iterate through all the elements and filter out arrays with empty dictionaries. data. ...

Exploring the power of React Leaflet and the exciting possibilities of React Leaflet

I'm currently in the process of implementing the draw functions on a leaflet map. I started off by creating a new app with just react-leaflet installed. I used npx create-react-app and installed the following packages: npm install react react-dom lea ...

Requesting information from a model using a JavaScript variable in a cshtml file in an ASP.NET application

Is there a way to use a JavaScript variable to retrieve a specific item from an array stored in a model? Below is a code snippet: function CreateCategoryList() { var limit = @(Model.CategoriesCount.ToString()); for (i=0; i<limit; ...

Typescript: Creating a new type by filtering an interface for matching properties

Imagine you have an interface structured like this: interface endpoints { "/api/user/{id}": { get: operations["getUserGET"]; }; "/api/user/add": { put: operations["addUsingPUT"]; }; ... } Is it pos ...

Focus on all of the individual items except for the one that was just selected

Within the function thirdNavFunction, I am seeking a way to specifically target all instances of the .third-nav classes, excluding the one that has been clicked on. This must be accomplished without utilizing jQuery. How can I achieve this? var thirdNav = ...

JavaScript if else statement with 3 different scenarios

I'm having trouble figuring out why this code isn't working. It seems like there might be a conflict between the testRed and testGreen functions. If that's the case, could someone please suggest a better approach to solving this issue? Code: ...

Exploring the process of setting up a datasource for Select2 in October CMS using the integrated Ajax Framework

Looking to utilize the extensive AJAX framework provided by October CMS to populate a Select2 box with data. The process of using a remote dataset in Select2 involves the following steps: $(".js-data-example-ajax").select2({ ajax: { url: "https://a ...

Discovering the following solution in JavaScript

I am a beginner in the field of web development and seeking help in generating a specific output for a given problem: var totalRows = 5; var result = ''; for (var i = 1; i <= totalRows; i++) { for (var j = 1; j <= i; j++) { res ...

Modifying the default value setting in MUI Datepicker

Currently, I am utilizing version @mui/x-date-pickers ^6.17.0. Here is the custom date picker I am using: https://i.stack.imgur.com/k8nF1.png Upon clicking the input field, the placeholder switches and a value gets appended. However, modifying the input ...

Error: [$controller:ctrlreg] - The controller registration has failed

I am currently exploring the world of AngularJs and attempting to display options from a json file. However, I keep encountering the following error message: "Error: [$controller:ctrlreg]" Below is the code snippet I am working with: var sj = angular. ...

When the parent div contains at least four divs, show the scroll arrow containers

In my code, there is a parent div that holds multiple child divs. If the number of child divs within the parent div exceeds 4, I want to show the scroll arrow containers. If it's less than 4, then those arrow containers should not be displayed. The ...

Fulfill the promise in AngularJS and assign it to a different factory

Presenting my factory below: .factory('UserData', ['User', '$q', function(User, $q) { var deferred = $q.defer(); return { user: null, get: function() { var _this = this; _this. ...

Create an object that may have any number of keys, but must have at least one key defined

Is there a way to accomplish this task? type Plant = "rose" | 'tulip' | 'daisy' type PlantCollection = { [p in Plant]?: number } const validPlantCollection: PlantCollection = { rose: 1, daisy: 2 } const emptyCollectionShouldBeRejec ...

The system has removed all content within the fields

I have created a code to generate a dynamic table. The problem I am facing is that when there are multiple rows in the table, clicking on the delete button deletes all field values instead of just deleting the data for the specific row where the delete b ...