How to extend an object to a function as arguments?

I have an object that takes arguments, I would like to distribute the objects, so each property is an argument in this function.

What am I doing wrong in my code?

const args = {
    a: 1
    b: 2
}

const fn = (a, b) => a + b

// i am trying with no success
console.log(fn(...args))
+10
source share
4 answers

You can use ES6 object destructuringfor the passed parameter, and then just pass in your object.

const args = {a: 1, b: 2}

const fn = ({a, b}) => a + b
console.log(fn(args))
Run codeHide result

You can also set default values ​​for these properties.

const args = {b: 2}

const fn = ({a = 0, b = 0}) => a + b
console.log(fn(args))
Run codeHide result

+7
source

, , . . Object.values (ES 2017), .

const args = {
  a: 1,
  b: 2
}

const fn = (a, b) => a + b

fn(...Object.values(args));

, , Object.values . , a b, Object.keys(args) .

+18

:

const fn = ({a, b}) => a + b
0

, , , . . , , . , , .

const args = {
    a: 1,
    b: 2,
    argumentify: function () { 
        return [this.a, this.b]; 
    }
};

const fn = (a, b) => a + b;

console.log(fn(...args.argumentify()));

:

1) , .

2) ( ( ) ).

3) .

0

Source: https://habr.com/ru/post/1691464/


All Articles