0

I came across a course, where the instructor used the following function arguments

const filteredBody = filteredObj(req.body, "name", "email");

Then he defined the function as the follows:

const filteredObj = (obj, ...allowedFields) => {
  const newObj = {};
  Object.keys(obj).forEach((el) => {
    if (allowedFields.includes(el)) {
      newObj[el] = obj[el];
    }
  });

  return newObj;
};

I am new to Javascript and I am having trouble understanding how he converted the arguments "name","email" into an array of allowedFields using ...allowedFields.

Saptaparnee
  • 25
  • 1
  • 1
  • 5

1 Answers1

2

When you prefixed last parameter in a function with ... it becomes rest parameter, which will cause all remaining parameters to be placed within a standard JavaScript array.

allowedFields in the below code becomes rest parameter which allows a function to accept an indefinite number of arguments as an array.

const filteredObj = (obj, ...allowedFields) => {
  const newObj = {};
  Object.keys(obj).forEach((el) => {
    if (allowedFields.includes(el)) {
      newObj[el] = obj[el];
    }
  });

  return newObj;
};
Sanket Shah
  • 2,888
  • 1
  • 11
  • 22