I need to destruct an object that some of the variables may already have a value.
let foo = 1, bar, baz = 'Hello';
const config = { foo: 42 };
({ foo, bar, baz } = config);
console.log({ foo, bar, baz });
This gives me
{
"foo": 42,
"bar": undefined,
"baz": undefined
}
But what I really want is
{
"foo": 42,
"bar": undefined,
"baz": "Hello"
}
I want to rewrite the value if there is a value with a same name in config
, if there's not, use its original value instead.
I can't assign default value while destructuring since the values are assigned previously.
({ foo = 1, bar, baz = 'Hello' } = config);
I know I can assign it like this but it's too clunky since there are more than 20 variables.
({ foo = foo, bar = bar, baz = baz } = config);
Is there a better way to write it without repeating x = x
all the time?