Organize a method's for-loop using JavaScript modules

I have a function that looks like this:

function createModifiedList(people){
    const modifiedList = []
    for (let i = 0; i < people.length; i++){
          modifiedList.push({
            name: person.firstName + " " + person.lastName,
            jobTitle: person.jobTitle,
          })
    }
    return modifiedList
}

Given a list of people, this function constructs a slightly altered version of the original list.

I am wondering if there is a way to pass an object that gets constructed during any step of the for loop as a parameter?

I aim to make this function modular for future reuse. In my actual codebase, which is much larger, this change would greatly enhance its efficiency, although the scenario remains similar.

Therefore, I would like to include an argument where I can input something like:

{
     name: person.firstName + " " + person.lastName,
     jobTitle: person.jobTitle,
}

And for subsequent function calls, I could provide:

{
     name: person.firstName + " " + person.lastName,
     bio: person.bio,
}

The method should then recognize that this is the object that needs to be added at each iteration of the for-loop.

Is there a way to achieve this functionality?

Thank you!

Answer №1

To enhance the flexibility of your code, consider passing the hard coding of the object as a parameter instead of keeping it within the makeSummary function. This approach allows you to define helper functions according to your specific requirements.

function makeSummary(people, helper){
    const myList = []
    for (int i = 0; i < people.length; i++){
          myList.push(helper(people[i])
    }
    return myList
}


function helper1(person){
  return {
      fullName: person.firstName + " " + person.lastName,
      title: person.title,
  }
}

function helper2(person){
  return {
      fullName: person.firstName + " " + person.lastName,
      description: person.description,
  }
}

//execute like this
makeSummary(people, helper1)
makeSummary(people, helper2)

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

Vue router-link alert

Hey there! I'm currently diving into a Vuejs3 Project and recently integrated Primevue into it. I added it to my main.js file and imported the Menubar component into my App.vue. While testing, everything seems to be working perfectly fine except for t ...

Ways to allocate space evenly between components of the same size in React Native

As a beginner in Javascript and React-native, I have been experimenting with the technology to assess its viability for potential use in my current workplace. However, I have encountered some challenges with the user interface. To enhance my understanding ...

Exploring the functionality of a personalized hook using the useSelector method

I have developed a custom hook and I am in the process of testing it independently. However, I am encountering an issue where I need to wrap the hook inside a Provider to proceed further. The error message I am getting is displayed below: Error: could not ...

Using JavaScript to send formatted text through POST requests in a Rails application

Within APP A, I have the following formatted text: A beautiful painting because I created it because an artist endorsed it because my cat loves it I can access this formatted text in index.html.erb through product.body_html, which I then load into a Ja ...

Use jQuery's change method to initiate a hidden file input

Want to create a fake file input using an anchor tag and trigger the hidden file input with jQuery? Looking for some advice on how to make this happen. Check out my current attempt here. I'm not sure if I'm on the right track with this, so any g ...

An issue with Nuxt.js causing body parameters to not be passed successfully while using this.$http.post

I've encountered an issue where using the @nuxt/http this.$http.post and this.$http.patch methods is causing problems with parsing body parameters during posting. Strangely, it used to work perfectly fine before, leaving me unsure of where to even beg ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Issue with displaying PDF files on Google Chrome due to a software glitch

Recently, I encountered a puzzling issue on Google Chrome. I am not sure if the error lies with Google or within my code. When I set the div as display: none; and then show it again, the PDF view only shows a grey background. However, if I zoom in or out, ...

Automatically insert content into a div following the execution of an AJAX delete function using jQuery

I've been working on a feature to display an auto-populated message in the results div when a user deletes the last item from their favorites list, indicating that it is empty. However, I've hit a roadblock and can't seem to make it work. H ...

Transforming JSON format to another JSON format using AngularJS

I am in the process of setting up a questionnaire using angularjs. I have an array of responses that looks like the following, and I need to convert this object array into JSON format. How do I go about converting an object array into JSON format? ...

What is the best way to flatten a 2D array using TypeScript?

If I have an array structured like this: [0]: ["id_1"]: prop1: "abc" prop2: "def" ["id_2"]: prop1: "ghi" prop2: "jkl" [1]: ["id_3"]: prop1: "mno" prop2: "pqr" ["id_4"]: prop1: "stu" ...

Utilizing React, generate buttons on the fly that trigger the display of their respective

Looking for a way to dynamically display 3 buttons, each of which opens a different modal? I'm struggling to figure out how to properly link the buttons to their respective modals. Here's the code I've attempted so far: Button - Modal Code: ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

What is the best way to determine if an item qualifies as an Angular $q promise?

In my project, I have an existing API library that is not Angular-based. This library contains a method called .request which returns promises using jQuery.Deferred. To integrate this with Angular, I created a simple service that wraps the .request method ...

Generating various API calls and delivering them to a template (Express + Node.js + Facebook open graph)

I am currently developing a unique Express Node.js application that utilizes the extraordinary capabilities of this remarkable Facebook SDK. Allow me to present my existing route for the root: app.get('/', Facebook.loginRequired(), function (req ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...