0

I want to make a function which can take any number of arguments. I can make function with fix arguments but I'm not able to solve with n arguments.

Example:

const first = { x: 2, y: 3};
const second = { a: 70, x: 4, z: 5 };
const third = { x: 0, y: 9, q: 10 };

const firstSecondThird = extend(first, second, third);
// { x: 2, y: 3, a: 70, z: 5, q: 10 }

const secondThird = extend(second, third);
// { a: 70, x: 4, z: 5, y: 9, q: 10 }`
adiga
  • 34,372
  • 9
  • 61
  • 83
Chris_007
  • 829
  • 11
  • 29
  • 2
    Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – yqlim Feb 13 '19 at 02:44
  • So Object assign in reverse? – epascarello Feb 13 '19 at 02:44
  • 1
    @YongQuan that one is for fixed arguments i want to make function with n arguments. – Chris_007 Feb 13 '19 at 02:45
  • It's not clear: are you asking about how to merge objects? Or are you asking about how to handle a variable number of function parameters? – Daniel Beck Feb 13 '19 at 02:45
  • @BarotShalin have you read _all_ the listed answers? – yqlim Feb 13 '19 at 02:45
  • 1
    @DanielBeck i want to merge objects without overwriting and with n arguments. I can solve for fixed arguments. – Chris_007 Feb 13 '19 at 02:46
  • You may want to re-think what you are trying to do. As opposed to creating a function that can have a dynamic amount of parameters, give the function an object or an array that contains all the arguments. – Spangle Feb 13 '19 at 02:55

1 Answers1

1

You could use the Rest parameters to get all the parameters into an array and then use spread syntax inside a reduce to merge them recursively:

const first = { x: 2, y: 3},
      second = { a: 70, x: 4, z: 5 },
      third = { x: 0, y: 9, q: 10 };

const extend = (...params) => params.reduce((r,p) => ({ ...r, ...p }), {})

console.log(extend(first, second, third))
console.log(extend(second, third))

If you want to give preference to the properties of earlier objects, then you have to reverse the arguments before using reduce:

const first = { x: 2, y: 3},
      second = { a: 70, x: 4, z: 5 },
      third = { x: 0, y: 9, q: 10 };

const extend = (...params) => params.reverse().reduce((r, p) => ({ ...r, ...p}), {})

console.log(extend(first, second, third))
console.log(extend(second, third))
adiga
  • 34,372
  • 9
  • 61
  • 83