1

I have a function which is defined as below

  function getProperties({
    url, listName, stage,
  }) {
    return {
      url,
      listName,
      currentStage: stage,
    };
  }

If I call this function as

getProperties({
  url: '<URL>',
  stage: '<stage>',
})

it should return

{
  url,
  currentStage: stage,
} 

So basically I want the function to return only those values which were actually passed as parameter to this function.

  • You just need to make couple of checks and return what you *need* to return. – dfsq Jan 11 '18 at 10:01
  • This becomes tedious job if the arguments list if big. – dhawalBhanushali Jan 11 '18 at 10:05
  • What else does this function do? Because if it only returns props (like identity function) then it doesn't make any sense. You can rename one param without such function. – dfsq Jan 11 '18 at 10:10
  • This is just an example. This function has several such arguments passed. Job of this function is to return the key-value pair with the same/different key name only if the passed object contains the key. – dhawalBhanushali Jan 11 '18 at 10:14
  • 2
    It's not possible with destructuring. You should have a generic pick function, such as described in https://stackoverflow.com/q/25553910/218196 . – Felix Kling Jan 11 '18 at 10:19
  • also possible duplicate of [Succinct/concise syntax for 'optional' object keys in ES6/ES7?](https://stackoverflow.com/q/47892127/1048572) – Bergi Jan 11 '18 at 12:55

1 Answers1

0

You can assign stage parameter to currentStage, assign [...arguments].pop() to a local variable if there are arguments, else set the variable to a plain object; check if the variable contains "stage" property, if the property is defined delete the property and set {currentStage} as an object to be assigned to the returned object

function getProperties({url, listName, stage: currentStage} = {}) {
  const o = [...arguments].pop() || {};
  return Object.assign(o, "stage" in o ? delete o.stage && {
    currentStage
  } : void 0)
}

console.log(getProperties()); // {}

console.log(getProperties({
  url: "<URL>",
  stage: "<stage>",
})); // {"url": "<URL>", "currentStage": "<stage>"}

console.log(getProperties({listName:"<abc>"})); // {"listName": "<abc>"}
guest271314
  • 1
  • 10
  • 82
  • 156