Search code examples
javascriptecmascript-6destructuring

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.


Solution

  • 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);
    }