Traversing an array in JavaScript to create a new array

I have a function that returns an array based on a condition. Here is the code snippet:

const operationPerResource = (resource: ResourceTypes): OperationTypes[] => {
  const operations = cases[resource] || cases.default;
  return operations;
};

Now, I need to iterate over an array of objects with a {label: string, value: string} type using the above function.

First, I transform the enum into an array:

const resources = transformEnumToArray(ResourceTypes);

const operations = operationPerResource(resources[0].value).map((value: any) => ({
  label: value,
  value
}));

The problem is that the above function only gives results for the first item in the array. I want to iterate over all items in the array and get back the available operations for each resource.

Whenever I select a resource from the select-box, I want to print the correct output. I am using the operationPerResource function to achieve this:

Since resources are an array of objects, I need to iterate over them to get the correct operations each time:

Example:
Resource: Name1 => Operations for Name1 [3 Items]
Resource: Name2 => Operations for Name2 [2 Items]
Resource: Name3 => Operations for Name3 [5 Items]

My goal is to make the process dynamic, so that clicking on a specific resource gives back the expected results each time.

I only want to print the results of each resource individually, not all together.

I'm facing a challenge in achieving this. Any assistance would be highly appreciated.

Answer №1

My suggestion is to use a nested map() function to map the resources array with the array returned from the operationPerResource() function

const operations = resources.map((r) => {
  return operationPerResource(r.value).map((value: any) => ({
      label: value,
      value
    })
  })
})

Answer №2

It appears that there is a desire to iterate through all resource types and combine the mapping results from each one. This essentially creates an array of arrays. To streamline this process, you can use the following logic:

const resourceTypes = transformEnumToArray(ResourceTypes);

const operations = [];

resourceTypes.forEach(resourceType => {
    const operationsForResource = operationsPerResource(resourceType.value);
    Array.prototype.push.apply(operations, operationsForResource.map((value: any) => ({
        label: value,
        value
    })));
});

operations will then contain a consolidated array of all the mapped results.

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 handle a very large JSON output in Node.js?

Working with shell.js to run unix commands in node.js and using bull for task queuing. The process involves providing an array of tasks: { "tasks": [ { "name": "task1", "command" ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

Sending an Array from a ReactJS Frontend to a Django Backend using JavaScript and Python

I successfully created a website using Django and React JS. In my project, I am working on passing an array named pict from the frontend JavaScript to the backend Python in Django. let pict = []; pictureEl.addEventListener(`click`, function () { console ...

What could be the reason for the collapse/expansion feature not functioning properly following the addition of

Why isn't my JavaScript code working? It was functioning correctly until I added the next block: <div class="collapse" id="collapse-block"> I have a collapse block (id='collapse-block') which contains 3 other collapse blocks inside. ...

Update the dropdown field selection to the color #333 with the help of javascript

I am facing an issue with a dropdown field that has placeholder text and options to select. Initially, both the placeholder text and the options were in color #333. However, I managed to change the color of the placeholder text to light grey using the foll ...

Building Vertical Tabs with external JS for loading custom visuals

I am trying to figure out how to display the visuals I created in an alternate page within my Vertical tabs. The tabs are already styled, and I have omitted the CSS due to its length. The HTML file I am working with is test.html, and the visuals are in the ...

What is the best way to ensure a toggle button retains its state when navigating between different React Routes

I've been working on implementing a dark mode toggle in JavaScript using React. I'm utilizing Material-UI for my page design and I've successfully made the button switch the theme of the entire page upon clicking. However, I've encounte ...

Library for adjusting the x axis scaling accurately

I need to find a JavaScript chart library that can support lines and zooming for handling a large amount of data. One issue I have encountered with other libraries is scaling the x-axis based on date and time data provided in strings: y=[43,56,34,63....] ...

What is preventing the audio from playing in Safari?

Recently, I developed a small JavaScript program that is meant to play the Happy Birthday tune. This program utilizes setInterval to gradually increase a variable, and depending on its value, plays or pauses certain musical notes. However, I encountered ...

Is it possible to resolve the issue with error code TS7016 stating that the declaration file for module '@angular/compiler' could not be found?

After integrating SignalR into my Angular Frontend, I encountered an error with code TS7016. import { ViewCompiler } from '@angular/compiler'; Attempting to resolve the issue, I executed the command: npm i --save-dev @types/angular__compiler ...

Encountering an ArrayIndexOutOfBoundsException despite increasing the array size to match the original array length

Currently facing a challenge on CodingBat.com called "frontPiece". The task is to return an array containing the first two elements of the original array. While this seems straightforward, handling edge cases like an empty array or an array with only one e ...

Encountered an error while attempting to compare 'true' within the ngDoCheck() function in Angular2

Getting Started Greetings! I am a novice in the world of Angular2, Typescript, and StackOverflow.com. I am facing an issue that I hope you can assist me with. I have successfully created a collapse animation for a button using ngOnChanges() when the butto ...

Navigating the browser view across an extensive HTML page without relying on scrollbars

I have a large HTML page (approximately 7000x5000) and I need to be able to move the user's view around with JavaScript. Disabling the ability for the user to scroll by hiding the browser scrollbars using overflow:hidden on the HTML element is easy. ...

The CSRF token in Laravel Blade seems to be unreachable by Vue

Having a blade with the following code snippet. <meta name="csrf-token" content="{{ csrf_token() }}"> <covid-form> </covid-form> Inside the covid-form component, there is a form structure like this: <form @submit.prevent="send"&g ...

Inject object into data attribute

I currently have data stored in a specific attribute like this: <div data-id=""> Within my markdown file, I also have a frontmatter variable like this: id: rick My goal is to pass that variable into the data-id attribute, which only accep ...

Algorithm for generating an array of integers through mathematical manipulation

Looking for a mathematical function that can generate arrays with all possible permutations of specific integers? For example: private static final int[][] x = {{1}}; private static final int[][] y = {{1,2},{2,1}}; private static final int[][] z = {{1,2,3 ...

Is it typical to experience a forced reflow violation and page offset?

After implementing a position: fixed on-scroll feature for my navbar, I noticed an error being thrown by the DOM stating: [Violation] Forced reflow while executing JavaScript took ms during every scroll event. It seems that this could be caused by layout t ...

disabling past dates in Bootstrap calendar

How can I disable past dates in Bootstrap easily? <script type="text/javascript"> $(function(){ $('.datepicker').datepicker(); }); </script> Date: <input type="text" class="datepicker"></input> I have added the ...

Exploring an Array Based on User's Input with JavaScript

Looking to implement a search functionality for an array using AJAX. The array is pre-populated with values, and the user will input a value in a HTML text box. If the entered value is found in the array, it should display "Value found", otherwise "not f ...

Angular's observables were unable to be subscribed to in either the constructor or ngOnInit() functions

Currently, I am incorporating an observable concept into my application. In this setup, a service is called by component1 to emit an event that is then subscribed to by component 2. Below is the code snippet for reference: Service Code export class Mes ...