Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript.

But what about accepting any number of objects as parameters in a function?

This is my current implementation:

function merge<T>(objA: T, objB: T){
  return Object.assign(objA, objB);
}

With this, I can use the function like this:

console.log(`${mergeObject2.age}, ${mergeObject2.name}`);

But how do you declare a function when the number of objects is unknown..?

For example, like this:

const mergeObject2 = merge({name: 'Niels'}, {age: 39}, {hobby: 'all'});

Thank you.

If I were to call the function like this:

const mergeObject2 = merge({name: 'Niels'}, {age: 39});

console.log(`${mergeObject2.age}, ${mergeObject2.name}`);

The output would be:

39, Niels

But how would you handle it with more objects..?

Answer №1

Essentially, in TypeScript, if you need to accept a varying number of parameters, all parameters must have the same type (which can be a union type). For example:

function myFunction(a: boolean, b: string, ...rest: Array<number | string>) {
    // ...
}

(You can also express Array<number | string> as (number | string)[].)

This function requires at least two fixed arguments (boolean and string) followed by any number of additional arguments that are either number or string. The additional parameters are grouped into an array with the same type (number | string in this case). You can use if statements to narrow down the type when dealing with a specific element from that array.

If you don't have any fixed parameters like a and b, you can directly start with the rest parameter.

If you intend to utilize Object.assign in your implementation, you will need to make the first one required (or explicitly specify Object.assign's first argument). Here's an example of implementing a merge function:

function merge<T extends object>(target: T, ...sources: T[]): T {
    return Object.assign(target, ...sources);
}
const mergedObject = merge({name: "Niels"}, {age: 39}); 
console.log(`${mergedObject.age}, ${mergedObject.name}`);

Playground link

This is essentially just a slightly more restricted version of Object.assign.


If you want to avoid modifying the initial object ({name: "Neils"}), consider adding an empty object at the beginning like so: {}.

Answer №2

If you want to access all arguments passed to a function, you can utilize the arguments object in ES5. This object acts like an array and holds the values of all arguments passed into the function.

function calculateSum(){
  let sum = 0;
  for(let i=0;i<arguments.length;i++){
    sum += arguments[i];
  }
  console.log(sum);
}
calculateSum(1,2,3);

To combine multiple objects into one, you can use this approach:

function combineObjects(){
  let finalObj = {};
  for(let i=0;i<arguments.length;i++){
    finalObj = {...finalObj,...arguments[i]};
  }
  console.log(finalObj);
}
combineObjects({id:1},{name:"sam"},{age: 25});

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

In MUI v5, the Autocomplete default value is not set

When I try to use the defaultValue prop in the Autocomplete component of MUI v5, the value always ends up being undefined. This is a snippet from my code: const vehicles = [ { name: "Toyota", model: "Camry" }, { name: "Ford&qu ...

Ensure that the three.js script remains in a fixed position on a page that can be

Is there a way to make a 3D model created with three.js have a fixed position on a scrollable page, like a background while the rest of the content scrolls normally? Are there any CSS techniques or additional script elements that can be used to achieve thi ...

dynamic jquery checkbox limit

I am working with the following HTML code: <input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1 <input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2 &l ...

"Exploring the depths of Webpack's module

This is my first venture into creating an Angular 2 application within MVC Core, utilizing TypeScript 2.2, Angular2, and Webpack. I have been closely following the Angular Documentation, but despite referencing the latest NPM Modules, I encounter errors w ...

Modifying various items depending on the variable's value

I'm attempting to adjust various variables depending on which button the user clicks. For instance, there are three buttons: <button id="button1" onclick="isClicked(this.id)">B1</button> <button id="button2" onclick="isClicked(this.id) ...

typescript error: referencing a variable before assigning a value to it in function [2454]

I am currently in the process of creating a store using nextJS I have two variables that are being assigned values from my database through a function let size: Size let ribbonTable: Ribbon async function findSizeCategory(): Promise<v ...

Dynamic property access using optional chaining in JavaScript

My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid. export const theme = { headers: { h1: { }, h6: { color: '#828286' }, }, } console.in ...

Organize an array of objects in JavaScript into a structure with nested children

I am facing a challenge with organizing an array of objects based on parentId and sort values. I need to create a nested array with 'children' and ensure proper sorting. Consider the following data: [{ id: 1, sort: 2, parentId: null ...

Exploring the latest whatwg-fetch update with TypeScript version 2.5.3

Within my TypeScript project, I am currently utilizing "whatwg-fetch": "2.0.3" as the latest version of this polyfill. Additionally, for types, I am using version "@types/whatwg-fetch": "0.0.33", and everything functions smoothly when working with TypeScri ...

Moving the legend around in vue-chartJS

As someone just starting out with Vue-ChartJs, I've become quite intrigued by this: https://i.sstatic.net/j1S0z.png I'm wondering how to move the legend to the bottom of the graph. Can anyone help me with that? ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

The intricate scripting nestled within the jQuery function

When using jQuery, I am looking to include more codes within the .html() function. However, I also want to incorporate PHP codes, which can make the writing style quite complex and difficult to read. Is it possible to load an external PHP/HTML script? fu ...

The application ceases to function properly following the update of npm and node on MacOS

I made a huge mistake by updating npm and node versions from 3.10.10 and 6.10.2 to 5.6.0 and 9.3.0, respectively. Now my app is not functioning properly and I am feeling quite desperate. Every time I try to run it, I encounter the following error: /Users ...

Disable link 2 when link 1 is clicked

Looking to create a feedback form with two exclusive links. Want to ensure that if someone clicks the first link, they cannot click the second link and vice versa. Interested in exploring options like using cookies to prevent multiple clicks or possibly ...

Encountering an issue with Typescript Vue class-based components in Laravel Mix: issue arises when attempting to set property 'render' on an undefined object

I have been using Laravel Mix to compile my Vue components, incorporating TypeScript and class-based components. Each class is exported from the component, and every component is required by the context in the main application script. However, during rende ...

When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but ...

Error: Attempting to assign a value to the property 'running' of an undefined variable

While working with Nuxt.js, I encountered an issue related to reading the running property of my client object. Here is the HTML code snippet: <b-button v-show="!(projectSelecter(project.ID)).isStarted" //this work just fine variant="success" c ...

Storing deeply nested arrays of objects with Mongoose leads to MongoDB storing empty objects

Here's the issue I'm facing: I am trying to save nested objects with mongoose in mongodb, but when I save them, the nested objects end up empty. I have attempted various solutions found online, such as pushing objects and populating, but none o ...

What is the best way to enhance a state's capabilities in Machina.js?

When using Machina.js (version 0.3.6), how can I instantiate a modified FSM constructor where both the child and parent FSMs define behaviors in the same states? Here is the code snippet: var _ = require('lodash'); var machina = require('m ...

Typescript - any of the types imported from a module

Currently, my code looks like this: import * as Types from '../schema/types'; and I'm looking to achieve something along the lines of: let a: Types; This would signify that a should be one of the various types exported from the file types. ...