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

Is there a way to retrieve the value of an element by clicking on its corresponding button using MUI framework?

I am working on a dashboard feature where I need to update the status by clicking on it. However, I am facing an issue with changing the state value upon clicking. Here is my component: <MenuItem> <Button fullWidt ...

Using React to showcase a base64 image representation

I'm struggling to show an image that has been sent from my Node/Express server to my React application. I've tried looking at solutions on other platforms, but so far nothing has worked for me. Let me outline the steps I have taken: The image is ...

Learn how to effortlessly integrate and utilize a bpmn file in a Vue component by leveraging the raw-loader

As a newcomer to bpmn-js, I am facing the challenge of importing and utilizing a .bpmn file within a vue.js component (BPMNViewer.vue). Despite my efforts in researching, I could only find recommendations to use the raw-loader. Consequently, I am currently ...

Retrieving a numerical value from a constantly changing string

The string is constantly changing. For example: Date15:Month8:Year1990 Is there a way to extract the number 15 without using substring, since the values are always different? I am looking to extract only the number after "Date" and before ":". ...

Playing a game of rock, paper, scissors with two players using JavaScript

Hello! I am a beginner in JavaScript and I am trying to create a simple rock, paper, scissors game. However, when I run the code, I receive two prompt messages and an error saying 'TypeError: playerOneChoice is not a function'. What mistake did I ...

Control the HTML button's state according to the information received from the server

I am currently working with datatable Jquery and using an ajax call to retrieve data from the server. Let's assume that the database consists of three attributes: "Attribute1, Attribute2, Status". Depending on the Status attribute, I need to enable or ...

Retrieve the bounding rectangle of a div that has the CSS style `display: contents` using the getBoundingClientRect

My objective is to apply styling and obtain the bounding box of an entire "row" within a CSS grid, including features like highlighting when hovering over it. To achieve the styling aspect, I make use of the display: contents property, so that the styles ...

Is it possible to use regex to replace all content between two dashes, including any new

I have a specific set of dashed markers that I am looking to update based on the content of $("#AddInfo"). If the field is not empty, I want to replace everything between the markers. Conversely, if $("#AddInfo") is empty, I need to remove all text betwe ...

Animate the CSS when the content is within the viewport using pagepiling.js integration

I'm currently working on animating content as it enters the viewport. However, I've encountered an issue where jQuery (used to check if the content is in the viewport) isn't functioning properly alongside pagepiling.js (). I suspect this mig ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

Error encountered in ASP.NET MVC application when using jQuery POST method: data is null

I am currently utilizing a PartialView and injecting it into a <div> from another PartialView to create a popup modal using the Bootstrap Modal. Although my Bootstrap Modal is displaying correctly, it is not functioning as intended. The following are ...

Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out. You can find the page I am referring to at: The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script: ...

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

Utilizing JQuery Ajax to dynamically replace elements using JQuery functions

My issue is as follows... I am using AJAX and jQuery to populate a form. When the user makes a selection from a dropdown menu, AJAX retrieves data based on the choice and populates the form with this data. Sometimes, new elements are created when the AJA ...

Tips for implementing event.preventDefault() with functions that require arguments

Here is a code snippet that I'm working with: const upListCandy = (candy) => { /* How can I add event.preventDefault() to make it work properly? */ axios.post("example.com", { candyName: candy.name }).then().ca ...

Error: [BITFIELD_INVALID_RANGE]: The bitfield flag or number entered is not valid: 3214336

Currently working on a Discord Dashboard project, but encountering an unusual error: Invalid bitfield flag or number 3214336. This issue arises when attempting to retrieve the guilds that a user has MANAGE_GUILDS permission for. Below is the snippet of my ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

The issue arises with proptypes validation while implementing material-ui components

Just embarked on a new ReactJS project and ran into a plethora of errors when I integrated material-ui. One of the errors looked like this: bundle.js:12441 Warning: Failed Context Types: Calling PropTypes validators directly is not supported by the prop ...

ng-bind stops updating after entering text into input field

I am a newcomer to AngularJS and I have encountered an issue that I am struggling to resolve. Although I found a similar question on stackoverflow, the solution provided did not work for me. The problem I am facing is that when I input text into any of the ...

Tips for refreshing the apollo cache

I have been pondering why updating data within the Apollo Client cache seems more challenging compared to similar libraries such as react-query. For instance, when dealing with a query involving pagination (offset and limit) and receiving an array of item ...