One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome?

Brief Description:

 
routes = [
{ name: 'vehicle', activated: true},
{ name: 'userassignment', activated: true},
{ name: 'relations', activated: true},
{ name: 'journeys', activated: true},
{ name: 'expenses', activated: true} 

];

Your Task - Develop a function that can perform the following actions on the array above:

  1. Set all members' property "activated" to false
  2. Choose one specific member and set its "activated" property to true based on its 'name'
  3. If the chosen member is 'journeys' or 'expenses', set them to true AND also set the 'relations' member to true

I have implemented the following code to accomplish this task, but my senior wants a smarter solution.

 
highlightActiveRoute(array: any[], chosen: string) {
  array.forEach(element => {
    element.activated = false;
    if (element.name === chosen) {
      element.activated = true;
      if (element.name === 'journeys' || element.name === 'expenses') {
        this.routes[2].activated = true;
      }
    } 
  });
}

I'm unsure if I can make it smarter, but perhaps you can provide some inspiration. Thank you!

Answer №1

This code snippet demonstrates how to highlight the active route using ArrayIterators in ECMAScript 2015. It ensures that no element in the array changes its position, providing a reliable solution:

toggleActiveRoute(array: any[], selected: string) {
array.forEach(item=>{item.isActive = false});
if(['journeys','expenses'].includes(selected))
{  
    array[array.findIndex(item=>{return item.name==='relations'})].isActive = true;
    array[array.findIndex(item=>{return item.name==='expenses'})].isActive = true;
    array[array.findIndex(item=>{return item.name==='journeys'})].isActive = true;
}
else
{
    array[array.findIndex(item=>{return item.name===selected})].isActive = true;
}

return array;
}

Answer №2

I took the liberty of making some minor enhancements to your code. Firstly, I streamlined the process by only updating the variable element.activated once instead of twice as before. Additionally, I simplified the structure of the code to enhance readability. I hope these improvements prove to be beneficial for you. Best of luck with your project!

highlightActiveRoute(array: any[], chosen: string) {
    array.forEach(element => {
        element.activated = element.name === chosen; 
        if (element.activated 
            && (element.name === 'journeys' || element.name === 'expenses')) {
                this.routes[2].activated = true;
        } 
    });
}

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

The elements within the NativeScript components are failing to show the data received from the Django API

My Django API is set up to provide a list of movies titles with their corresponding IDs. I've implemented a movie service in TypeScript that retrieves the list of movie titles and IDs using the GET operation. In my NativeScript project, I have two f ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

Allowing SVGs to be clickable without disrupting the functionality of YouTube videos

I'm experiencing an issue with the overlapping of the svg and YouTube elements. If you hover your mouse over, just to the right of the svg and click, instead of opening the video, it redirects you back to the previous page. Clicking on the area betw ...

Issues arise when using the select element

Struggling with submitting my list of items from a select in AngularJS. This is my first time posting here and I'm still finding my way around. The issue lies in using ng-repeat in my HTML to display all items. When the screen loads, it only shows: { ...

Error message: When attempting to redirect to another route, there is a type error with 'this' as it is implicitly assigned the type 'any'

I'm facing an issue with a component I've built using hooks. I want it to redirect to a different route when a function is called and the server response is received. However, my TypeScript is throwing an error: Type error: 'this' impl ...

Type-constrained generic key access for enhanced security

While attempting to create a versatile function that retrieves the value of a boolean property using a type-safe approach, I encountered an issue with the compiler not recognizing the type of my value. type KeyOfType<T, V> = keyof { [P in keyof T a ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

Transformed the Next.js Pages Router into an Application Router

Looking to make a change in my API written with Nextjs's Pages Router. Currently, it serves as a proxy for downloads and I am interested in converting it to the App Router method. Does anyone have any guidance on how to go about implementing this? imp ...

Encountering an Issue when Registering New Users in Database using Next.js, Prisma, and Heroku

Currently, I am immersed in my inaugural full-stack app development project, which is aligning with an online course. Unfortunately, I have encountered a major stumbling block that has persisted despite hours of troubleshooting. The issue arises when I try ...

Angular 2 Issue: Error Message "Cannot bind to 'ngModel'" arises after FormsModule is added to app.module

I've been struggling with the data binding aspect of this tutorial for over a day now. Here's the link to the tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt1.html The error I keep encountering is: Unhandled Promise rejection: Tem ...

Assigning websockets to a global variable may cause them to malfunction

I'm utilizing websockets in conjunction with JavaScript and HTML5. Here is the code snippet I am currently working with: <input type="text" onFocus="so = new Websocket('ws://localhost:1234');" onBlur="so.close();" onKeyUp="keyup();"> ...

Obtain information from Firebase and display it in a list

I've been struggling to retrieve my to-do tasks from a firebase database, but unfortunately, no data is appearing on my view. Surprisingly, there are no errors showing up in the console. My journey led me to the point of "saving data" in firebase. H ...

Store the results in the database following the execution of a protractor test

I am completely new to angular protractor testing. I have created some test cases using the protractor framework with jasmine runner BDD style. Within a single test class, I have 10 to 12 specs, each with an expectation. Currently, I am running these tests ...

What could be the reason for the malfunction of my callback function?

This particular function is executed with the command node server const express = require("express"); const app = express(); const fs = require("fs"); const connectDb = require("./config/db"); const __init__ = (local = false) => { fs.writeFile( ...

What is the best way to handle errors generated by my jsdom.jqueryify callback function?

When running this code in node.js, the output is a stack trace of an error that occurs on line 9. Surprisingly, the error on line 7 seems to be 'absorbed' by Node. Even when wrapped in a try/catch statement, the detailed stack trace output is not ...

How can one properly utilize material-ui CSS?

Just starting out with material-ui and react, I'm currently following this palette customization guide from Material-UI. However, when attempting to replicate the example shown, I encountered the error: Cannot read property 'prepareStyles' ...

Is there a way to send the image object to the onclick function as it is being assigned?

I apologize if my question is a bit unclear, as I am currently teaching myself how to use javascript. I am working on generating image thumbnails dynamically and would like the ability for users to enlarge the image when they click on the thumbnails. The p ...

Tips and tricks for manipulating base64 images in Node.js

I have a unique challenge - I want to manipulate a base64 picture by adding just one extra pixel. My goal is to send a base64 image string (e.g. data:image/png;base64,iVBORw0KG...) from my express server. Let's say the image is 100x100px and I need to ...

Mismatch between generic types

When working with this code, I encounter a syntax error at m1 and m2. The error message states: Type 'T' is not assignable to Type 'boolean' or Type 'T' is not assignable to Type 'string' interface customMethod { ...