Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to write a function that handles dynamic method chaining

So lets say I have the following method

api.post('users')
        .set(key,value);
        .send(data)
        .expect(201)

I was curious in javascript how I could set up a function to dynamically call/chain .set on the first method based on the number of keys in an object? So if I had the object foo = {a: 1, b:2 , c:2}

the function would behave like the following

 api.post('users')
            .set(a,1)
            .set(b,2)
            .set(c,3)
            .send(data)
            .expect(201)
like image 493
Austin Davis Avatar asked Feb 15 '26 18:02

Austin Davis


1 Answers

The function can simply call .set in a loop:

function setMultiple(api, values) {
    for (var key in values) {
        if (values.hasOwnProperty(key)) {
            api = api.set(key, values[key]));
        }
    }
    return api;
}
like image 59
Barmar Avatar answered Feb 17 '26 06:02

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!