0

I have a JavaScript module that exported with arrow function with 3 parameters, the following example:

// getMonth.js module

export default (date, type, ...rest)  => {
  // Represent this return exmaple
  return date + ' ' + type + ' ' + rest
}

In the main file, I have an array that I want to Assign the keys of the array as function's parameters

import getMonth from '../modules/month.js'
  
let splitedParams = ['2016/07/14', 'full']

getMonth({date, type, ...rest} = splitedParams)

But this implementation isn't right and I got some error, How can I do this?

Thanks

1
  • getMonth.apply(undefined, splitedParams) Commented Dec 14, 2016 at 15:46

2 Answers 2

1

Use function.apply()

import getMonth from '../modules/month.js'

let splitedParams = ['2016/07/14', 'full']

getMonth.apply(null, splitedParams)

Or use the spread operator: ...

getMonth(...splitedParams)

See it demonstrated in this example below:

let splitedParams = ['2016/07/14', 'full']

//using Function.prototype.apply()
getMonth.apply(null, splitedParams);

//using the spread operator
getMonth(...splitedParams);

function getMonth(date, type) {
  console.log('getMonth() - date: ', date, 'type: ', type);
}

Sign up to request clarification or add additional context in comments.

Comments

1

Use the spread syntax ... to assign the values from the array to the function parameters:

import getMonth from '../modules/month.js'

const splitedParams = ['2016/07/14', 'full']

getMonth(...splitedParams)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.