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

Updating State and Modifying URL in ReactJS when Input Changes

I am currently attempting to modify the state and URL onChange within a <Input type='select'> element, utilizing reactstrap. import React, {Component} from 'react' import { Input, } from 'reactstrap' export default ...

What is the process of displaying text within a link?

I have a basic webpage where I want the text to display from a link. Here is my website: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Encyclopedia</title> <link href="test.css" re ...

Access specific data from a jQuery event

How can I retrieve the value of a custom attribute called itemID in order to include it in the URL just like I do with id? Here is the JavaScript code: <script type="text/javascript"> $(document).ready(function(){ $('.eventImage').cl ...

I am looking to set a maximum display length of 5 items for every list in VueJS

For example, in Udemy's filter option, when you click on the "See More" button, it only shows 5 items. I tried creating a similar option using Vue, but when I clicked to see more, it displayed the entire list. I want to limit this list to only 5 item ...

Ways to eliminate a value once a checkbox is deselected

I am currently developing a search box that includes three separate fields which will be populated with data using AJAX based on the user's selection. Here is the HTML structure I have implemented: <div id="states"> <input type="checkbo ...

What is the best way to recreate WordPress categories using static HTML pages?

As I consider converting my WordPress website to static HTML pages, I'm planning on editing them in tools like Responsive Site Designer, Dreamweaver, or SublimeText. My main concern is how I will organize content into categories without the convenien ...

Ways to establish communication between an iframe and its parent website

I have a website embedded in an iframe that is not on the same domain. Both websites belong to me, and I would like to establish communication between the iframe and the parent site. Is this achievable? ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

Having trouble capturing emitted events in VueJs

I am working with 2 components: MenuItem.vue <styled-menu-item :label="label" :selected="selected" @click="onClick(label)"> ... methods: { onClick(e) { this.$emit('menu-change', e); } } and Sidebar.vue <StyledSidebar @menu-cha ...

Tips for switching the background image in React while a page is loading?

Is there a way to automatically change the background of a page when it loads, instead of requiring a button click? import img1 from '../images/img1.jpg'; import img2 from '../images/img2.jpg'; import img3 from '../images/img3.jpg& ...

Ensuring that all checkboxes have been selected

I have 5 checkboxes all with the attribute name set as relative-view. To confirm that all of them are checked, I know how to verify the first and last one: expect(element.find('input[name="relative-view"]').first().prop("checked")).toBe(true); ...

In the world of web development with JavaScript, jQuery, and EasyUI, we often encounter situations where the parameter

function formatData_original() { // convert obj_num2.formatter = function(value, rec) { var baseStr='&nbsp;&nbsp;' + rec.s_date + '<a class="easyui-linkbutton" href="javascript:void(0);" plain= ...

overlay appears as I reveal the slide-out menu

Struggling with adding an overlay to an expanding navigation bar, similar to Youtube's overlay when the slide-out nav is open. Need help with the implementation. Here is the javascript code for the expanding navigation using jQuery: 'use strict ...

Nuxt JS Route Changes Not Triggering Page Scroll to Top

How can I ensure that the page always scrolls to the top when routing changes in Nuxt? In an attempt to achieve this, I have added the following code to my app/router.scrollBehavior.js file: export default function (to, from, savedPosition) { return { x ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

What is the best method to retrieve the v-model values of v-for components when iterating with numeric indices?

Within my template, I have form-group components that are being iterated over based on the value of a select element (an integer). My goal is to access the values of these iterated v-models, but I am struggling to get it right. TEMPLATE <b-form-g ...

unable to successfully npm install canvas

For my GitHub repository, please visit here This project was actively developed until November of last year, after which I did not commit any changes. Today, I attempted to run the project again but encountered the following error. My current system versi ...

When utilizing await/async in TypeScript with Axios, the return type may be incorrect

UPDATE: After some investigation, it turns out the issue was not related to Axios or TypeScript but rather a strange IDE configuration problem. Starting fresh by recreating the environment and .idea folder solved the issue. While working with Axios in Typ ...

Crafting a robust and secure password using Yup and Formik while receiving personalized error notifications

My Password Validation Dilemma I'm in the process of developing a password field that can assess the strength of the input provided. In a different response, I came across a regex that I could utilize to validate whether the input meets specific crit ...

Is it possible to verify if a user is accessing a webpage through Electron?

If I were interested in creating a basic Electron application that notifies the user upon reaching example.com, is this achievable? If yes, then how can I determine if the user is on a particular webpage? ...