Reputation: 922
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
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
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