Brimby
Brimby

Reputation: 922

Using default values in object destructuring while retaining any un-defaulted values

Is it possible to set some default parameters via destructuring while still retaining any extra values not accounted for in the default? ex:

var ob = {speed: 5, distance: 8}

function f({speed=0, location='home'}) {
    return {speed: speed, location: location, /* other keys passed in with their values intact */}
}

f(ob) // Would like to return {speed: 5, location: 'home', distance: 8}

Edit: My function is unknowing as to the names of the keys that might be passed in as extras. Eg: the function has no knowledge of whether it will be receiving/returning a key named 'distance', or a key named 'foo'. So I'm thinking some kind of use of ...rest followed by ...spread.

Upvotes: 1

Views: 83

Answers (2)

Felix Kling
Felix Kling

Reputation: 817238

Is it possible to set some default parameters via destructuring while still retaining any extra values not accounted for in the default?

Not at the moment, no. You can store the defaults in a separate object and use Object.assign:

var ob = {speed: 5, distance: 8};
var defaults = {speed: 0, location: 'home'};

function f(obj) {
    return Object.assign({}, defaults, obj);
}

f(ob);

Upvotes: 2

Warren Mira
Warren Mira

Reputation: 242

You can't with current es6 but you can using rest operator available on via stage 2 preset.

function f({speed= 0, location: 'home', ...others}) {
   return Object.assign({}, {speed, location}, others);
}

Upvotes: 2

Related Questions