Differences Between Object.keys().map() and Array.map()

I'm seeking a rationale for why Approach A is considered superior to Approach B.

Approach A:

const transformCompanyOptions = (companies: Array<{id: string, name: string}>, selectedId: string) => {
  return companies.map(key => {
    return {
      value: key.id,
      label: key.name,
      checked: key.id === selectedId
    }
  })
};

Approach B:

const transformCompanyOptions = (companies: Array<{id: string, name: string}>, selectedId: string) => {
 const ret = Object.keys(companies).map((key) => {
    const newCompany = {};
    newCompany['value'] = companies[key].id;
    newCompany['label'] = companies[key].name;
    if (companies[key].id === selectedId) {
      newCompany['checked'] = true;
    }
    return newCompany;
  });
  return ret;
};

Your insights are greatly appreciated!

Answer №1

Approach A is:

  • more concise
  • less wordy
  • tidier
  • offers improved performance (no need to retrieve all keys using Object.keys as in approach B)

Moreover, there are ways to enhance approach A further:

const transformCompanyOptions = (companies: Array<{id: string, name: string}>, 
    selectedId: string) => {
  return companies.map(c => ({ 
      value: c.id,
      label: c.name,
      checked: c.id === selectedId
    }))
};

@TKoL highlighted in the comments:

Avoid referring to the argument in .map as a key, since it actually represents a company itself rather than a key within an array

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

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Unable to retrieve an array in SAPUI5 and assign it to a JSONModel

I encountered an issue with accessing an array where I stored data from a model read operation. The array, named aData, contains row data for a table and everything seems to be working correctly as all the data is present. This code snippet is executed af ...

Unable to fetch information from the local host using an AJAX request and PHP script

I'm having trouble retrieving the <p> elements echoed in my PHP script. I need a solution that allows me to style these <p> nodes using a JavaScript function without refreshing the page. Can someone help me with this issue? Here is my PHP ...

Determining the Winning Team in C Algorithm

I'm working on a tournament data storage project. The input includes the number of teams (n) and the number of games they will play (n!). Additionally, I need to collect the team names and their respective results. Here's an example: Input: 3 6 ...

The datepicker in Vuetify is failing to display any dates

My date picker modal expands correctly, but the dates are not showing up. https://i.stack.imgur.com/azC1w.png The datepicker functions perfectly on the Codepen demo, displaying the dates as expected. However, when I try to implement the same code in my ap ...

Can you explain the mechanics behind Google Voice Search? And is there an available API for it?

Is this the right place to ask how the voice-activated search feature on Google's homepage functions? I'm curious about whether it utilizes Flash, a plugin integrated into Google Chrome, or some other method to access the microphone. The idea of ...

Why is it possible to assign a variable holding a char array to a pointer in C, but attempting to take the address of that same pointer is not allowed?

Let's examine the following code snippet: char stringy[] = "There's too much confusion, I can't get no relief!"; char *pStringy; pStringy = stringy; It's interesting how this code compiles without any errors. Although stringy ...

JavaScript Multiplicative Persistence Problem Resolved by Implementing Efficient Solution that Executes in a Timely

I am currently facing an issue with the following problem: Your task is to create a function called persistence, which takes a positive parameter num and calculates its multiplicative persistence. Multiplicative persistence refers to the number of times y ...

Why is it necessary to type in localhost in the address bar when using node.js and socket.io instead of simply opening the client.html file directly?

I am intrigued by this topic. My suspicion is that it may be related to the temporary file created by socket.io, but I'm struggling to fully understand it... ...

Automatically refresh the D3 Sunburst visualization when the source json is modified (items added or removed)

I'm a beginner in D3 and I'm attempting to update the chart dynamically if the source JSON is modified. However, I'm facing difficulties in achieving this. Feel free to check out this plunkr Js: var width = 500, height = 500, radi ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

Generate a dynamic regular expression using regex characters

If I am looking to find matches for the following files: /foo/bar/baz/x /foo/bar/baz/y/z I can create a regular expression like this: new RegExp('^/foo/bar/baz/.*') But the question arises - how can I instruct the RegExp constructor to interp ...

Exploring the analysis of JavaScript and CSS coverage throughout various pages or websites

The Chrome Dev Tools JavaScript and CSS Coverage Drawer is quite impressive, but there is one thing that could make it even better. It would be great if it could remain active without restarting its analysis every time you visit a new page. I wish I could ...

Utilize MaxMind GeoIP2 to identify the city accurately

I have been using this simple code to retrieve the city name through the maxmind service (geoip2). It has been working flawlessly and I am grateful to a fellow member of this site who shared this code with me. However, there is an issue when the user&apos ...

Execute function when button is not active

Within my Angular 2 application, I have a form along with the following code snippet that relates to the button responsible for submitting the form. <button (mouseover)="showMesageValidation()" class="edm-button" type="submit" [disabled]="!f.valid"> ...

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

When I remove the `return false` statement in my code, my AJAX call executes successfully. However, keeping it in prevents the call from

I am using jQuery to send an AJAX POST request without refreshing the page. I have tried using the return false command to prevent the page from refreshing, but then the AJAX POST request doesn't go through. If I remove the return false command, the A ...

Initiate the Material TextField onChange event from within a nested component

I am currently working on a component that looks like this: class IncrementField extends Component { inputRef; changeValue() { this.inputRef.value = parseInt(this.inputRef.value) + 1; } render() { const { ...other } = this.props; return ( ...

Having trouble getting sweet alert to work with my PHP script

I’m integrating Sweet Alerts 2 into my webpage in order to prompt the user when trying to delete something. However, I'm encountering an issue where the PHP file is not being triggered when the user presses delete and the Sweet Alert does not appear ...