Discover how to iterate through an array following a map operation and generate a new array based on conditional statements

data.risk.scatterIndices.investments.map((el: any) => el.name) || []

I have a mapping function that generates an array like this:

["pension","realestate","balance","kupot"]

This is the condition I want to use to translate this array into a new array:

`
if(key === 'balance'){
    key = 'עוש ומזומן'
} else if(key === 'realestate'){
    key = 'נדלן'
} else if(key === 'pension'){
    key = 'פנסיה'
} else if(key === 'kupot'){
    key = 'קופות'
}
`

Expected output:

["קופות","עוש ומזומן","נדלן","פנסיה"]

How can I achieve this?

Answer №1

To transform the array elements, you can utilize the map function.

const arr = ['pension', 'realestate', 'balance', 'kupot']

const res = arr.map(key => {
  if (key === 'balance') {
    return 'עוש ומזומן'
  } else if (key === 'realestate') {
    return 'נדלן'
  } else if (key === 'pension') {
    return 'פנסיה'
  } else if (key === 'kupot') {
    return 'קופות'
  } else {
    return 'N/A'
  }
})

console.log(res)

Answer №2

To convert values in an array, simply utilize a "For" loop as demonstrated below:

for(let i=0; i < array.length; i++){

  switch (array[i]) {
    case "pension":
      array[i] = 'פנסיה';
      break;

    // Include more cases in the switch statement for additional conversions
  }
}

Answer №3

To simplify the process, you can create an object with replacements and map through the array to replace values if they exist in the object.

const
    replacements = { balance: 'עוש ומזומן', realestate: 'נדלן', pension: 'פנסיה', kupot: 'קופות' },
    array = ["pension", "realestate", "balance", "kupot", "some value"],
    result = array.map(k => replacements[k] || k);

console.log(result);

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

Tips on documenting important occurrences while the cursor is positioned within a text field

https://i.sstatic.net/K28wT.png Having some trouble with key events on a remote control interface. Everything works fine except when the cursor is inside a text field, my key events stop working. If anyone has experience with key events, please help me o ...

Looking to organize a table in jhipster but unsure of the process. Can someone provide guidance on how

For the past week, I have been delving into jhipster and attempting to incorporate a sortable table. Could someone clarify how exactly the jhiSort and jhiSortBy functions operate? I am struggling to grasp the purpose of the predicate, ascending, and call ...

Error encountered numerous times within computed signals (angular)

I have incorporated signals into my Angular application. One of the signals I am using is a computed signal, in which I deliberately introduce an exception to see how it is handled. Please note that my actual code is more intricate than this example. pu ...

Minimizing the computational time of adding numbers in a Go program

I encountered an issue with the code I wrote, as the code test site rejected it due to processing time. In an attempt to reduce the processing time, I implemented a Two Pointers algorithm and Goroutine (although unsure if correctly). Despite these efforts, ...

The ion-chip close function activates upon closure, while the ion-item button event is

While trying to utilize an ion-item as a button, I encountered an issue where an ion-chip with a delete event was triggering the ion-item event instead of the intended ion-chip event. Even when using event.stopPropogation, the problem persisted. Is there ...

jQuery function for shuffling the order of a random div?

Upon loading the page, I have implemented a code that randomizes the order of the child divs. Here is the code snippet: function reorder() { var grp = $("#team-posts").children(); var cnt = grp.length; var temp, x; for (var i = 0; i < cnt; ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...

Array data that has been rearranged appears duplicated

I'm looking to shuffle the values of an array. I have multiple checklists, and I receive values with the code below: $arrayplayer[0] = 10 $arrayplayer[1] = 1 $arrayplayer[2] = 17 $arrayplayer[3] = 9 Every time I want to randomize the order of the ar ...

What is the best way to update a Textfield in each row of a table using PHP and AJAX when a different textfield in the same row is changed

My JavaScript code adds a row with two cells to a table when a button is clicked. One cell contains a livesearch textfield, and the other cell has a quantity textfield whose value is supposed to dynamically change based on the livesearch results. I'v ...

How does array.sort rearrange the elements of the original array?

What's the reason for the array "matrix[0]" getting sorted too when Arrays.sort(check) is executed? int[] check = matrix[0]; Arrays.sort(check); I have found a solution by using Systemcopy, but what is the explanation behind this? ...

What is the best way to locate a table of a specific class using jQuery selectors?

Is there a way to specifically target a table with the class "d" using jQuery selectors? I'm having trouble making it work... var dTableTags = $(".d table"); For instance, an example table would look like this... <table id="thetable" class="d"&g ...

Utilize your access token to send a message through Google Business Messages

Currently, I have successfully set up a method to send messages using the Google Business Messages API from an agent to a user through NodeJS. const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); This process requires authenticatio ...

Maximizing Efficiency: Utilizing a Single Panel across Multiple HTML Files with jQueryMobile

Can a panel defined in index.html be used on another page, such as results.html? Or do I have to define the panel on every page and duplicate the HTML code on each page? Because I want the panel to be consistent across all pages. This is the panel in my ...

Can simplemodal cause issues with ASP.NET AJAX controls?

Can simplemodal disrupt ASP.NET AJAXified controls? It seems like after displaying the modal, using an AJAX feature, closing the modal and then reopening it, the AJAX controls stop functioning. Could this issue be caused by simplemodal or is it just a coi ...

My chat in an Iframe does not seem to reload the content when the user navigates to a different page

I am currently facing an issue with a chat feature on my website that is displayed within an iframe. The chat itself is hosted on chat.A.com, which is on a different server than my site (A.com). To embed the chat on A.com, I am using an iframe with the s ...

Encountering a Next.js installation error due to the inability to locate the module fs

Having trouble with the installation of a new Next.js 14 app. I've searched on Google and Stack Overflow but haven't been able to find a solution. I'm stuck at this point. Can anyone offer some assistance? What I have attempted: npx creat ...

What is the best way to send props in Typescript?

Recently, I delved into the realm of typescript and encountered a challenge with passing props. My project involves a movie search functionality which follows this component chain: App -> Hero (a large div displaying everything) -> Container (divs co ...

The Angular2 test case reveals a missing provider for NgControl

ng test displays an error message below, but the functionality works correctly in practice. Error: Template parse errors: No provider for NgControl (" <div class="form-group"> <label class="control-label">Location</label&g ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

Storing User Information in Discord.js to Prevent Spam

I'm currently working on creating an anti-spam feature using Discord.js. However, I am facing a challenge in saving data such as the timestamp of the user's last message sent. ...