If I understand correctly, it seems the spread syntax is a good fit for what you need.
The spread syntax "...
" allows you to "spread" the key/value pairs from a source object (ie test
) to a target object (ie destruct
):
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
}
const destruct = {
// {a,b}: test <-- invalid syntax
...test // equivalent using the "spread" syntax
};
console.log(destruct)
Additionally, if you wanted to select a subset of keys from a source object and spread those into a target object then this can be achieved by the following:
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
}
/* Spread subset of keys from source object to target object */
const welcomeOnly = {
...({ a, b } = test, { a, b })
}
console.log('exclude goodbye, show welcomes only:', welcomeOnly);
The second example works by destructing the source object (ie test
) into an object, with the subset of keys that we want (a
and b
).
In the scope of that expression (ie everything between the (
and )
), these keys are accessible as local variables. We take advantage of this, and pass those to a new object (ie { a, b }
). Because the new object is declared after the ,
, it is returned as the result of the expression.